Skip to content

Commit 1098ea5

Browse files
committed
Fixed issue with unbound events breaking call order
Ticket: jeromeetienne#10 Patch: https://gist.github.com/8e281e63aa2fa0fcdbf8
1 parent d3e810b commit 1098ea5

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

microevent-test.js

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ test('.trigger() calls the handler once for each call', function () {
3535

3636
events.trigger('suprise');
3737
events.trigger('suprise');
38-
assert(handler.callCount === 2, 'Expected handler to be called twice');
38+
assert(handler.called === 2, 'Expected handler to be called twice');
3939
});
4040

4141
test('.trigger() passes additional arguments through to handler', function () {
@@ -48,21 +48,42 @@ test('.trigger() passes additional arguments through to handler', function () {
4848
assert(handler.args.lastCall[2] === 'three', 'Expected third argument of handler to be three');
4949
});
5050

51+
test('.trigger() allows handlers to be unbound in handler', function () {
52+
var A = createSpy();
53+
var B = createSpy(function () { events.unbind('suprise', B); });
54+
var C = createSpy();
55+
56+
events.bind('suprise', A);
57+
events.bind('suprise', B);
58+
events.bind('suprise', C);
59+
60+
events.trigger('suprise');
61+
assert(A.called === 1, 'Expected A to be called once');
62+
assert(B.called === 1, 'Expected B to be called once');
63+
assert(C.called === 1, 'Expected C to be called once');
64+
65+
events.trigger('suprise');
66+
assert(A.called === 2, 'Expected A to be called twice');
67+
assert(B.called === 1, 'Expected B to be called once');
68+
assert(C.called === 2, 'Expected C to be called twice');
69+
});
70+
5171
// Run the tests.
5272
if (require.main === module) {
5373
run(test.suite);
5474
}
5575

5676
// Test Suite Helpers
5777

58-
function createSpy() {
78+
function createSpy(fn) {
5979
return function spy() {
80+
fn && fn.apply(this, arguments);
81+
6082
var args = Array.prototype.slice.call(arguments);
6183
spy.args = (spy.args || []);
6284
spy.args.push(args);
6385
spy.args.lastCall = args;
64-
spy.called = true;
65-
spy.callCount = (spy.callCount || 0) + 1;
86+
spy.called = (spy.called || 0) + 1;
6687
};
6788
}
6889

microevent.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,9 @@
2525
trigger: function(event /* , args... */){
2626
this._events = this._events || {};
2727
if (event in this._events === false) { return; }
28-
for(var i = 0; i < this._events[event].length; i++){
29-
this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
28+
var callbacks = (this._events[event] || []).slice();
29+
while (callbacks.length) {
30+
callbacks.shift().apply(this, Array.prototype.slice.call(arguments, 1));
3031
}
3132
}
3233
};

0 commit comments

Comments
 (0)