Skip to content

Commit

Permalink
Much smaller/managable fix for jashkenas/backbone#3455
Browse files Browse the repository at this point in the history
We should eventually pull in their changes but for a hope in actually
getting this fix in production I opted to do this instead for now.
  • Loading branch information
James Hartig committed Feb 12, 2015
1 parent 31031f8 commit efdb54e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
18 changes: 17 additions & 1 deletion bedrock.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,13 +220,29 @@
for (var id in listeningTo) {
obj = listeningTo[id];
obj.off(name, callback, this);
if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id];
if (remove || !eventsLeftForContext(obj, this)) {
delete this._listeningTo[id];
}
}
return this;
}

};

// Fix memory leak reported in https://github.com/jashkenas/backbone/issues/3453
// Though their fix is probably better, its a lot larger to try and port right now
function eventsLeftForContext(obj, ctx) {
var i, l, n;
for (n in obj._events) {
for (i = 0, l = obj._events[n].length; i < l; i++) {
if (obj._events[n][i].ctx === ctx) {
return true;
}
}
}
return false;
}

// Space literal reference used to split event strings.
var eventSplitter = ' ';

Expand Down
15 changes: 10 additions & 5 deletions test/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,21 +165,26 @@
e.trigger("foo");
});

test("stopListening cleans up references", 8, function() {
test("stopListening cleans up references", 10, function() {
var a = _.extend({}, Backbone.Events);
var b = _.extend({}, Backbone.Events);
var fn = function() {};
a.listenTo(b, 'event', fn).stopListening();
b.on('other', fn);
a.listenTo(b, 'all', fn).stopListening();
equal(_.size(a._listeningTo), 0);
equal(_.size(b._events), 0);
equal(_.size(b._events), 1);
a.listenTo(b, 'event', fn).stopListening(b);
equal(_.size(a._listeningTo), 0);
equal(_.size(b._events), 0);
equal(_.size(b._events), 1);
a.listenTo(b, 'event', fn).stopListening(b, 'event');
equal(_.size(a._listeningTo), 0);
equal(_.size(b._events), 0);
equal(_.size(b._events), 1);
a.listenTo(b, 'event', fn).stopListening(b, 'event', fn);
equal(_.size(a._listeningTo), 0);
a.listenTo(b, 'event', fn).listenTo(b, 'event', fn).stopListening(null, 'event');
equal(_.size(a._listeningTo), 0);
equal(_.size(b._events), 1);
b.off('other', fn);
equal(_.size(b._events), 0);
});

Expand Down

0 comments on commit efdb54e

Please sign in to comment.