From b085fa0099d75cf112e07ac580f282fb22afa7b9 Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Thu, 2 Dec 2010 09:59:26 -0500 Subject: [PATCH] Events#trigger ... making it safe to unbind your own event within a trigger() call. --- backbone.js | 6 ++++-- test/events.js | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/backbone.js b/backbone.js index 640fbb83..3031eb10 100644 --- a/backbone.js +++ b/backbone.js @@ -92,12 +92,14 @@ trigger : function(ev) { var list, calls, i, l; if (!(calls = this._callbacks)) return this; - if (list = calls[ev]) { + if (calls[ev]) { + list = calls[ev].slice(0); for (i = 0, l = list.length; i < l; i++) { list[i].apply(this, Array.prototype.slice.call(arguments, 1)); } } - if (list = calls['all']) { + if (calls['all']) { + list = calls['all'].slice(0); for (i = 0, l = list.length; i < l; i++) { list[i].apply(this, arguments); } diff --git a/test/events.js b/test/events.js index 83808428..cdc8e8df 100644 --- a/test/events.js +++ b/test/events.js @@ -39,4 +39,18 @@ $(document).ready(function() { equals(obj.counterB, 2, 'counterB should have been incremented twice.'); }); + test("Events: two binds that unbind themeselves", function() { + var obj = { counterA: 0, counterB: 0 }; + _.extend(obj,Backbone.Events); + var incrA = function(){ obj.counterA += 1; obj.unbind('event', incrA); }; + var incrB = function(){ obj.counterB += 1; obj.unbind('event', incrB); }; + obj.bind('event', incrA); + obj.bind('event', incrB); + obj.trigger('event'); + obj.trigger('event'); + obj.trigger('event'); + equals(obj.counterA, 1, 'counterA should have only been incremented once.'); + equals(obj.counterB, 1, 'counterB should have only been incremented once.'); + }); + }); \ No newline at end of file