Permalink
Browse files

slice the events array before looping through it and calling event ha…

…ndlers

prevents errors from handlers that mutate the events array, e.g. by unbinding other events.
  • Loading branch information...
1 parent 2a38718 commit d02dc67f1f2a712a5ec4fb94605caeae5d75b854 @olivernn committed Sep 21, 2012
Showing with 19 additions and 1 deletion.
  1. +1 −1 src/event_emitter.js
  2. +18 −0 test/tests/event_emitter_test.js
View
2 src/event_emitter.js
@@ -33,7 +33,7 @@
EventEmitter.prototype.emit = function(name) {
var args = Array.prototype.slice.call(arguments, 1)
- var events = prepareEvent.call(this, name)
+ var events = prepareEvent.call(this, name).slice()
for (var i = 0, length = events.length; i < length; i++) {
var callback = events[i].callback
View
18 test/tests/event_emitter_test.js
@@ -50,3 +50,21 @@ test("unbinding by callback and scope", 1, function() {
ee.emit("a")
})
+
+test("emitting events with callbacks that unbind events", function () {
+ var ee = new Model.EventEmitter,
+ eventName = 'test',
+ callbackCalled = false
+
+ var handler = function () {
+ ee.off(eventName, arguments.callee)
+ }
+
+ ee.on('test', handler)
+ ee.on('test', function () { callbackCalled = true })
+
+ ee.emit('test')
+
+ ok(callbackCalled)
+
+})

0 comments on commit d02dc67

Please sign in to comment.