Backbone.js: Dynamically adding events not firing -


i trying around backbone.js , along far, have got problem.

lets got root element , child element.

when document loads, create 3 "root" instances. root instance appends tag. each root instance creates 1 child instance creates

  • tag in ul tag.

    now child instance attach , onclick event

  • tag. unfortunately, won't work.

    i created fiddle:

    http://jsfiddle.net/fluxo/seje5/17/

    var child = backbone.view.extend({     template: _.template('<li>item '+count+'</li>'),     events: {         'click li': function() {          alert('listitem click child element');            }     },     initialize: function() {       _.bindall('render');        this.render();        }, render: function() {         this.$el.html(this.template())     } });  var root = backbone.view.extend({     template: _.template('<div><h3>list</h3><p /><ul></ul><hr />'),     events: {         'click li': function() {          alert('listitem click - root element');            }     },     initialize: function() {         _.bindall('render');         this.render();     },     render: function() {         this.$el.html(this.template());         $('body').append(this.el);         var item = new child();         this.$el.find('ul').append(item.$el.html());      } }); 

    the events created in root element fire, not ones in child element.

    am doing wrong?

  • you're doing 2 things wrong.

    first of all, child <li>, doesn't contain <li>:

    template: _.template('<li>item '+count+'</li>'), events: {     'click li': ... }, 

    so click li event won't anything. events bound view's el using delegate:

    delegateevents delegateevents([events])

    uses jquery's delegate function provide declarative callbacks dom events within view. [...] omitting selector causes event bound view's root element (this.el).

    so if want bind click handler directly view's el rather 1 of children, want leave out selector:

    events: {     'click': ... } 

    the next problem you're not inserting child element dom, you're copying html:

    this.$el.find('ul').append(item.$el.html()); 

    by appending item.$el.html() instead of item.el, you're grabbing correct html string , inserting html lose events in process; events bound dom object, item.el, not html string. can fix appending item.el:

    this.$el.find('ul').append(item.el); // or say, 2 approaches same this.$('ul').append(item.el); 

    demo: http://jsfiddle.net/ambiguous/k76jm/ (or http://jsfiddle.net/ambiguous/kfxhq/)


    Comments

    Popular posts from this blog

    jquery - Invalid Assignment Left-Hand Side -

    java - Play! framework 2.0: How to display multiple image? -

    gmail - Is there any documentation for read-only access to the Google Contacts API? -