Problems with binding events on subview in backbone.js

I am working on learning backbone.js and well it has been a bumpy road. Along the way I have come across several hiccups, but this one was a doozy and caused me all sorts of frustration. I was trying to to bind a change event to a select menu in one of my subviews. For the life of me I could not get the event to fire correctly. If I copied the exact same event to the parent view it worked just fine. This lead me to believe that I was experience a scope issue. There is lots of information on the web about breaking the scope of “this” in backbone.js which further lead me to believe this was the problem. But turns out that was not the problem at all. After a whole lot of confusion I lucky stumbled upon this post on stackoverflow

Unfortunately it looks like it was not the answer to the original posters problem, but it solved my issue.

According to the post, events in backbone.js are not actually bound to the changing element but rather the root element of the view and then delegated to the children from there. This is important if you are not actually inserting your the root element of your subview into the DOM, because then your events will not fire (which is exactly what I was doing).

So, this render function simply inserts the rendered template html into the DOM which fails to actually insert the views el into the DOM.

render: function() {
$('#anchorDiv').append( this.template(this) );
},

Something like this however will actually insert the view’s root element into the DOM which will (at least in my case) solved all my event issues.
render: function() {
$(this.el).html( this.template(this) );
$('#anchorDiv').append( this.template(this) );
},

I am really liking backbone.js as I think it is helping me better structure my applications. That being said, it has been tough to really learn and grasp how everything is supposed to work. This issue was not straight forward to me at all and hopefully might help somebody out there figure out why their events are not working like they thing they should.

Comments are closed.