documentcloud/backbone — Issue #794: bindToModel View property
Author: RStankov
Created: 2011-12-17 01:37:01+00:00
State: open

I have very often this pattern in some form:

SomeView = Backbone.View.extend({
initialize: function() {
this.model.bind('some:event:1', this.someAction1, this);
this.model.bind('some:event:2', this.someAction2, this);

this.collection.bind('some:event:3', this.someAction3, this);
this.collection.bind('some:event:4', this.someAction4, this);
},
// onClose is called when view.remove()
remove: function() {
this.model.unbind('some:event:1', this.someAction1);
this.model.unbind('some:event:2', this.someAction2);

this.collection.unbind('some:event:3', this.someAction3);
this.collection.unbind('some:event:4', this.someAction4);

Backbone.View.prototype.remove.call(this);
}
});

And I think it will be really great to make this just:

SomeView = Backbone.View.extend({
bindToModel: {
'some:event:1': 'someAction1',
'some:event:2': 'someAction2'
},
bindToCollection: {
'some:event:3': 'someAction3',
'some:event:4': 'someAction4'
}
});

The two special attributes ```bindToModel``` and ```bindToCollection``` will bind the events, and when ```view.remove()``` is called all events will be unbind before dom removal. I think this will save a lot of code (and bugs related to model event binding/unbinding). This will also make Backbone even more awesome :)

If you agree on having such API I'll be happy to provide an implementation, since I have several minor prototypes of this.