How to capture the key event from a view?
You can do this in the view initialize() function: _.bindAll(this, ‘on_keypress’); $(document).bind(‘keypress’, this.on_keypress);
You can do this in the view initialize() function: _.bindAll(this, ‘on_keypress’); $(document).bind(‘keypress’, this.on_keypress);
One way is: var ChildView = ParentView.extend({ events: function(){ return _.extend({},ParentView.prototype.events,{ ‘click’ : ‘onclickChild’ }); } }); Another would be: var ParentView = Backbone.View.extend({ originalEvents: { ‘click’: ‘onclick’ }, //Override this event hash in //a child view additionalEvents: { }, events : function() { return _.extend({},this.originalEvents,this.additionalEvents); } }); var ChildView = ParentView.extend({ additionalEvents: { ‘click’ … Read more
When you create a view, both listenTo and on add event handling. However, when the view is destroyed, the listenTo call will automatically remove the event handler. This prevents memory leaks and zombie event listeners. So, use on if you want to manage the handler yourself. Just make sure to call off. Otherwise, call listenTo.
When you do this: this.$el.html( this.subView.render().el ); You’re effectively saying this: this.$el.empty(); this.$el.append( this.subView.render().el ); and empty kills the events on everything inside this.$el: To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves. So you lose the delegate call that binds … Read more
I had to be absolutely sure the view was not just removed from DOM but also completely unbound from events. destroy_view: function() { // COMPLETELY UNBIND THE VIEW this.undelegateEvents(); this.$el.removeData().unbind(); // Remove view from DOM this.remove(); Backbone.View.prototype.remove.call(this); } Seemed like overkill to me, but other approaches did not completely do the trick.