Skip to content

Commit

Permalink
Fixed issue with unbound events breaking call order
Browse files Browse the repository at this point in the history
  • Loading branch information
aron committed Apr 28, 2014
1 parent d3e810b commit 1098ea5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
29 changes: 25 additions & 4 deletions microevent-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ test('.trigger() calls the handler once for each call', function () {

events.trigger('suprise');
events.trigger('suprise');
assert(handler.callCount === 2, 'Expected handler to be called twice');
assert(handler.called === 2, 'Expected handler to be called twice');
});

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

test('.trigger() allows handlers to be unbound in handler', function () {
var A = createSpy();
var B = createSpy(function () { events.unbind('suprise', B); });
var C = createSpy();

events.bind('suprise', A);
events.bind('suprise', B);
events.bind('suprise', C);

events.trigger('suprise');
assert(A.called === 1, 'Expected A to be called once');
assert(B.called === 1, 'Expected B to be called once');
assert(C.called === 1, 'Expected C to be called once');

events.trigger('suprise');
assert(A.called === 2, 'Expected A to be called twice');
assert(B.called === 1, 'Expected B to be called once');
assert(C.called === 2, 'Expected C to be called twice');
});

// Run the tests.
if (require.main === module) {
run(test.suite);
}

// Test Suite Helpers

function createSpy() {
function createSpy(fn) {
return function spy() {
fn && fn.apply(this, arguments);

var args = Array.prototype.slice.call(arguments);
spy.args = (spy.args || []);
spy.args.push(args);
spy.args.lastCall = args;
spy.called = true;
spy.callCount = (spy.callCount || 0) + 1;
spy.called = (spy.called || 0) + 1;
};
}

Expand Down
5 changes: 3 additions & 2 deletions microevent.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@
trigger: function(event /* , args... */){
this._events = this._events || {};
if (event in this._events === false) { return; }
for(var i = 0; i < this._events[event].length; i++){
this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
var callbacks = (this._events[event] || []).slice();
while (callbacks.length) {
callbacks.shift().apply(this, Array.prototype.slice.call(arguments, 1));
}
}
};
Expand Down

0 comments on commit 1098ea5

Please sign in to comment.