javascriptjquerytwitter-flight

Attach component to dynamically created elements with Twitter Flight


Been looking to figure out how with Twitter Flight can attach to dynamic created elements.

Having the following HTML

<article>Add element</article>

And the following component definition

var Article = flight.component(function () {
    this.addElement = function () {
        this.$node.parent().append('<article>Add element</article>');
    };

    this.after('initialize', function () {
        this.on('click', this.addElement);
    });
});
Article.attachTo('article');

Once a new element is created, the click event doesn't fire. Here's the fiddle: http://jsfiddle.net/smxx5/


Solution

  • Try attaching Article to each new article added:

    JSFiddle: http://jsfiddle.net/TrueBlueAussie/smxx5/2/

    var Article = flight.component(function () {
        this.addElement = function () {
            var newArticle = $('<article>Add element</article>');
            this.$node.parent().append(newArticle);
            Article.attachTo(newArticle);
        };
    
        this.after('initialize', function () {
            this.on('click', this.addElement);
        });
    });
    
    Article.attachTo('article');
    

    The Article.attachTo('article'); at the end, that runs once on load, will only attach to existing article elements.