diff --git a/cocos2d/core/event/event-listeners.js b/cocos2d/core/event/event-listeners.js index e27b02b7e7..621e8625de 100644 --- a/cocos2d/core/event/event-listeners.js +++ b/cocos2d/core/event/event-listeners.js @@ -4,60 +4,60 @@ var CallbacksHandler = require('../platform/callbacks-invoker').CallbacksHandler // Extends CallbacksHandler to handle and invoke event callbacks. function EventListeners () { CallbacksHandler.call(this); + this._invoking = null; + this._toRemove = []; + this._toRemoveAll = null; } JS.extend(EventListeners, CallbacksHandler); EventListeners.prototype.invoke = function (event) { - var list = this._callbackTable[event.type], - i, endIndex, lastItem, + var key = event.type, + list = this._callbackTable[key], + i, endIndex, callingFunc, target, hasTarget; + this._toRemove.length = 0; + this._invoking = key; + if (list) { if (list.length === 1) { list[0].call(event.currentTarget, event); - return; } - endIndex = list.length - 1; - lastItem = list[endIndex]; - for (i = 0; i <= endIndex;) { - callingFunc = list[i]; - target = list[i+1]; - hasTarget = target && typeof target === 'object'; - var increment; - if (hasTarget) { - callingFunc.call(target, event); - increment = 2; - } - else { - callingFunc.call(event.currentTarget, event); - increment = 1; - } - - if (event._propagationImmediateStopped || i + increment > endIndex) { - break; - } - // 为了不每次触发消息时都创建一份回调数组的拷贝,这里需要对消息的反注册做检查和限制 - // check last one to see if any one removed - if (list[endIndex] !== lastItem) { // 如果变短 - if (list[endIndex - 1] === lastItem) { - // 只支持删一个 - endIndex -= 1; - } - else if (list[endIndex - 2] === lastItem) { - // 只支持删一个 + target - endIndex -= 2; + else { + endIndex = list.length - 1; + for (i = 0; i <= endIndex;) { + callingFunc = list[i]; + target = list[i+1]; + hasTarget = target && typeof target === 'object'; + var increment; + if (hasTarget) { + callingFunc.call(target, event); + increment = 2; } else { - // 只允许在一个回调里面移除一个回调。如果要移除很多,只能用 event.stopPropagationImmediate() - return cc.error('Call event.stopPropagationImmediate() when you remove more than one callbacks in a event callback.'); + callingFunc.call(event.currentTarget, event); + increment = 1; } - if (list[i] !== callingFunc) { // 如果删了前面的回调,索引不加 - continue; - } - } - i += increment; + if (event._propagationImmediateStopped || i + increment > endIndex) { + break; + } + + i += increment; + } } } + this._invoking = null; + + // Delay removing + for (i = 0; i < this._toRemove.length; ++i) { + var toRemove = this._toRemove[i]; + this.remove(key, toRemove[0], toRemove[1]); + } + this._toRemove.length = 0; + if (this._toRemoveAll) { + this.removeAll(this._toRemoveAll); + this._toRemoveAll = null; + } }; module.exports = EventListeners;