Skip to content

Commit

Permalink
Call stopListening on behaviors onClose
Browse files Browse the repository at this point in the history
  • Loading branch information
samccone committed Apr 18, 2014
1 parent c68c1ab commit ac49a05
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 2 deletions.
37 changes: 36 additions & 1 deletion spec/javascripts/behaviors.spec.js
Expand Up @@ -338,10 +338,45 @@ describe("Behaviors", function(){
layout = new Layout();
layout.render();
layout.close();
expect(onCloseSpy).toHaveBeenCalled();
expect(onCloseSpy).toHaveBeenCalled(1);
});
});

describe("behavior instance events", function() {
var model, v, listenToSpy, onSpy;

beforeEach(function() {
listenToSpy = new sinon.spy();
onSpy = new sinon.spy();
model = new Backbone.Model();

v = new (Marionette.View.extend({
behaviors: {
cat: {
behaviorClass: (Marionette.Behavior.extend({
initialize: function() {
this.listenTo(model, "change", listenToSpy);
this.on("wow", onSpy);
}
}))
}
}
}));

v.close();
});

it("shoud unbind listenTo on close", function() {
model.set("klingon", "dominion");
expect(listenToSpy).not.toHaveBeenCalled();
});

it("shoud still be bound to 'on' on close", function() {
v.triggerMethod("wow");
expect(onSpy).toHaveBeenCalled();
});
});

describe("behavior model events", function() {
var modelSpy, collectionSpy, V, hold, m, testBehavior;
beforeEach(function() {
Expand Down
5 changes: 5 additions & 0 deletions src/marionette.behavior.js
Expand Up @@ -31,6 +31,11 @@ Marionette.Behavior = (function(_, Backbone){
_.extend(Behavior.prototype, Backbone.Events, {
initialize: function(){},

// stopListening to behavior `onListen` events.
close: function() {
this.stopListening();
},

// Setup class level proxy for triggerMethod.
triggerMethod: Marionette.triggerMethod
});
Expand Down
13 changes: 12 additions & 1 deletion src/marionette.behaviors.js
Expand Up @@ -22,7 +22,7 @@ Marionette.Behaviors = (function(Marionette, _) {
'delegateEvents', 'undelegateEvents',
'onShow', 'onClose',
'behaviorEvents', 'triggerMethod',
'setElement'
'setElement', 'close'
]);
}

Expand All @@ -38,6 +38,17 @@ Marionette.Behaviors = (function(Marionette, _) {
}, this);
},

close: function(close, behaviors) {
var args = _.tail(arguments, 2);
close.apply(this, args);

// Call close on each behavior after
// closing down the view.
// This unbinds event listeners
// that behaviors have registerd for.
_.invoke(behaviors, 'close', args);
},

onShow: function(onShow, behaviors) {
var args = _.tail(arguments, 2);

Expand Down

0 comments on commit ac49a05

Please sign in to comment.