Permalink
Browse files

CompositeView provides bindTo and invokes unbindFromAll in leave()

  • Loading branch information...
1 parent 554ca3a commit aba55f9fb03eb32498d6c731e5984bb827a6d591 @jasonm jasonm committed Sep 28, 2012
Showing with 35 additions and 0 deletions.
  1. +14 −0 lib/assets/javascripts/backbone-support/composite_view.js
  2. +21 −0 spec/javascripts/composite_view_spec.js
@@ -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);
@@ -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.