Skip to content

Instantly share code, notes, and snippets.

@pangloss
Created August 12, 2011 13:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pangloss/1141980 to your computer and use it in GitHub Desktop.
Save pangloss/1141980 to your computer and use it in GitHub Desktop.
// Allows you to specify events on the data tied to the view in the same way
// that you can specify dom events:
//
// dataEvents: {
// instanceName: {
// 'change:name': 'mothed',
// delete: 'otherMethod'
// }, ...
// }
registerDataEvents: function(unbind) {
if (!this.dataEvents) return;
if (!this.boundMethods)
this.boundMethods = [];
for (var modelName in this.dataEvents) {
var model = this.options[modelName],
events = this.dataEvents[modelName];
for (var key in events) {
var method = this[events[key]];
if (!method) throw new Error('Event "' + events[key] + '" does not exist');
method = _.bind(method, this);
model.bind(key, method);
this.boundMethods.push({target: model, event: key, method: method});
}
}
},
unregisterDataEvents: function() {
if (this.boundMethods) {
_.each(this.boundMethods, function(binding) {
binding.target.unbind(binding.event, binding.method);
});
}
},
MyView = Backbone.View.extend({
events: {
'click [data-state]': 'selectStatus',
'click .clear-deadline': 'clearDeadline',
'resize': '_reposition',
'click': '_onClick',
},
dataEvents: {
task: { 'change': 'onChange' },
taskStatus: {
'change:state': 'onChange',
'change:deadline': 'updateDeadline'
},
comments: {
'add': 'onChange',
'remove': 'onChange'
}
},
initialize: function() {
this.registerDataEvents();
},
close: function() {
this.unregisterDataEvents();
this.remove();
},
});
new MyView({task: t, taskStatus: ts, comments: c});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment