Skip to content
This repository has been archived by the owner on Jun 8, 2019. It is now read-only.

Commit

Permalink
CompositeView provides bindTo and invokes unbindFromAll in leave()
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonm committed Sep 28, 2012
1 parent 554ca3a commit aba55f9
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/assets/javascripts/backbone-support/composite_view.js
Expand Up @@ -6,11 +6,25 @@ Support.CompositeView = function(options) {
_.extend(Support.CompositeView.prototype, Backbone.View.prototype, {
leave: function() {
this.unbind();
this.unbindFromAll();
this.remove();
this._leaveChildren();
this._removeFromParent();
},

bindTo: function(source, event, callback) {
source.bind(event, callback, this);
this.bindings = this.bindings || [];
this.bindings.push({ source: source, event: event, callback: callback });
},

unbindFromAll: function() {
_.each(this.bindings, function(binding) {
binding.source.unbind(binding.event, binding.callback);
});
this.bindings = [];
},

renderChild: function(view) {
view.render();
this.children.push(view);
Expand Down
21 changes: 21 additions & 0 deletions spec/javascripts/composite_view_spec.js
Expand Up @@ -163,5 +163,26 @@ describe("Support.CompositeView", function() {
expect($("#test2").size()).toEqual(1);
expect(view.children.size()).toEqual(1);
});

it("removes any bindings that were bound via bindTo", function() {
var model1 = new Backbone.Model({}),
model2 = new Backbone.Model({}),
eventListener = sinon.spy(),
bindToView = new (Support.CompositeView.extend({
initialize: function(options) {
this.bindTo(options.model1, 'change', eventListener);
this.bindTo(options.model2, 'change', eventListener);
}
}))({
model1: model1,
model2: model2
});

bindToView.leave();
model1.trigger('change');
model2.trigger('change');

expect(eventListener.called).toBeFalsy();
});
});
});

0 comments on commit aba55f9

Please sign in to comment.