From e38901ca5279dbc5a27eec48e0964cf2895bee8c Mon Sep 17 00:00:00 2001 From: Graeme Yeates Date: Wed, 20 Jan 2016 13:28:50 -0500 Subject: [PATCH] Unbind on destroy; improve unbind logic --- lib/collection.js | 15 +++++++-------- lib/model.js | 16 ++++++++-------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/lib/collection.js b/lib/collection.js index db0588a..4f3c576 100644 --- a/lib/collection.js +++ b/lib/collection.js @@ -99,15 +99,14 @@ Backbone.Collection.prototype.ioUnbind = function (eventName, io, callback) { } var events = ioEvents[eventName]; if (!_.isEmpty(events)) { - if (callback && 'function' === typeof callback) { - for (var i = 0, l = events.length; i < l; i++) { - if (callback == events[i].cbLocal) { - this.unbind(events[i].name, events[i].cbLocal); - io.removeListener(events[i].global, events[i].cbGlobal); - events[i] = false; + if ('function' === typeof callback) { + _.each(events, function(event, index) { + if (callback == event.cbLocal) { + this.unbind(event.name, event.cbLocal); + io.removeListener(event.global, event.cbGlobal); + events.splice(index, 1); } - } - events = _.compact(events); + }, this); } else { this.unbind(eventName); io.removeAllListeners(globalName); diff --git a/lib/model.js b/lib/model.js index 1a5fea6..689e07c 100644 --- a/lib/model.js +++ b/lib/model.js @@ -64,6 +64,7 @@ Backbone.Model.prototype.ioBind = function (eventName, io, callback, context) { }; this.bind(event.name, event.cbLocal, (context || self)); io.on(event.global, event.cbGlobal); + this.once('destroy', _.bind(this.ioUnbind, this, event.name, io, event.cbLocal)); if (!ioEvents[event.name]) { ioEvents[event.name] = [event]; } else { @@ -97,15 +98,14 @@ Backbone.Model.prototype.ioUnbind = function (eventName, io, callback) { } var events = ioEvents[eventName]; if (!_.isEmpty(events)) { - if (callback && 'function' === typeof callback) { - for (var i = 0, l = events.length; i < l; i++) { - if (callback == events[i].cbLocal) { - this.unbind(events[i].name, events[i].cbLocal); - io.removeListener(events[i].global, events[i].cbGlobal); - events[i] = false; + if ('function' === typeof callback) { + _.each(events, function(event, index) { + if (callback == event.cbLocal) { + this.unbind(event.name, event.cbLocal); + io.removeListener(event.global, event.cbGlobal); + events.splice(index, 1); } - } - events = _.compact(events); + }, this); } else { this.unbind(eventName); io.removeAllListeners(globalName);