public
Created — forked from pangloss/dataevents.js

  • Download Gist
dataevents.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
// 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.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
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();
},
});
usage.js
JavaScript
1
new MyView({task: t, taskStatus: ts, comments: c});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.