Skip to content

Commit

Permalink
Events#trigger ... making it safe to unbind your own event within a t…
Browse files Browse the repository at this point in the history
…rigger() call.
  • Loading branch information
jashkenas committed Dec 2, 2010
1 parent d4dc736 commit b085fa0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
6 changes: 4 additions & 2 deletions backbone.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
14 changes: 14 additions & 0 deletions test/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.');
});

});

0 comments on commit b085fa0

Please sign in to comment.