Events#trigger ... making it safe to unbind your own event within a trigger() call.

This commit is contained in:
Jeremy Ashkenas
2010-12-02 09:59:26 -05:00
parent d4dc736a82
commit b085fa0099
2 changed files with 18 additions and 2 deletions

View File

@@ -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);
}

View File

@@ -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.');
});
});