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
now child instance attach , onclick event
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
delegatefunction provide declarative callbacks dom events within view. [...] omittingselectorcauses 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
Post a Comment