Created
September 11, 2013 18:38
-
-
Save thomsbg/6527888 to your computer and use it in GitHub Desktop.
Redefining delegateEvents() on a collection view to handle children's events too
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
App.Views.CommentList = Backbone.View.extend({ | |
childrenById: {}, | |
childSelector: 'div', | |
childView: function() { | |
return App.Views.Comment; | |
}, | |
// Bind child event handlers once, instead of once per child view | |
delegateEvents: function() { | |
// Call super | |
Backbone.View.prototype.delegateEvents.call(this); | |
var childView = _.result(this, 'childView'); | |
var childEvents = _.result(childView.prototype, 'events'); | |
var childrenById = this.childrenById; | |
var childSelector = this.childSelector; | |
// Loop through the child's events object, | |
_.each(childEvents, function(methodName, key) { | |
// Copied from Backbone | |
var match = key.match(/^(\S+)\s+(.+)$/); | |
var eventName = match[1]; | |
var eventSelector = match[2]; | |
// Join the childSelector and the eventSelector to make sure the event | |
// is coming from a child element | |
var selector = childSelector + ' ' + eventSelector; | |
// Append a namespace to the event name so that undelegateEvents() | |
// unbinds the events correctly. | |
eventName += '.delegateEvents' + this.cid; | |
this.$el.on(eventName, selector, function(evt) { | |
// Find the containing child element | |
var $child = jQuery(evt.currentTarget).closest(childSelector); | |
// Assume the child element's HTML id is the model id | |
var childId = $child.attr('id'); | |
// Look up the child view by model id | |
var view = childrenById[childId]; | |
if (view) { | |
// Call the specified handler on the child, if found | |
return view[methodName].call(view, evt); | |
} | |
}); | |
}, this); | |
return this; | |
} | |
}); | |
App.Views.Comment = Backbone.View.extend({ | |
// Do not delegate events here, handled by a parent view | |
delegateEvents: _.identity | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment