Skip to content

Commit

Permalink
Fixes listenToOnce memory leak.
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesplease authored and akre54 committed Nov 3, 2014
1 parent 71cecdc commit 459dc24
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
7 changes: 7 additions & 0 deletions backbone.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,13 @@
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
listeningTo[id] = obj;
if (!callback && typeof name === 'object') callback = this;
if (implementation === 'once') {
var cb = callback;
callback = function () {
this.stopListening.apply(this, _.rest(arguments));
return cb.apply(this, arguments);
};
}
obj[implementation](name, callback, this);
return this;
};
Expand Down
13 changes: 12 additions & 1 deletion test/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,14 +177,25 @@
equal(_.keys(a._listeningTo).length, 0);
});

test("listenToOnce cleans up references after the event has fired", 2, function() {
test("listenToOnce without context cleans up references after the event has fired", 2, function() {
var a = _.extend({}, Backbone.Events);
var b = _.extend({}, Backbone.Events);
a.listenToOnce(b, 'all', function(){ ok(true); });
b.trigger('anything');
equal(_.keys(a._listeningTo).length, 0);
});

test("listenToOnce with event maps cleans up references", 2, function() {
var a = _.extend({}, Backbone.Events);
var b = _.extend({}, Backbone.Events);
a.listenToOnce(b, {
a: function() { ok(true); },
b: function() { ok(false); }
});
b.trigger('a');
equal(_.keys(a._listeningTo).length, 1);
});

test("listenTo with empty callback doesn't throw an error", 1, function(){
var e = _.extend({}, Backbone.Events);
e.listenTo(e, "foo", null);
Expand Down

0 comments on commit 459dc24

Please sign in to comment.