Skip to content

Instantly share code, notes, and snippets.

@thomsbg
Created September 11, 2013 18:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomsbg/6527888 to your computer and use it in GitHub Desktop.
Save thomsbg/6527888 to your computer and use it in GitHub Desktop.
Redefining delegateEvents() on a collection view to handle children's events too
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