Javascript删除在对象中生成的事件侦听器

时间:2012-02-14 18:11:28

标签: javascript events

我使用下面的代码向主体添加事件侦听器,但我无法将其删除

this.events = {
    addEventListener : function(element, eventName, eventHandler, scope) {
        var scopedEventHandler = scope ? function(e) { eventHandler.apply(scope, [e]); } : eventHandler;
        if(document.addEventListener)
            element.addEventListener(eventName, scopedEventHandler, false);
        else if(document.attachEvent)
            element.attachEvent("on"+eventName, scopedEventHandler);
    }
}
this.events.addEventListener( document.body, "keydown", this.keyEvent, this);

1 个答案:

答案 0 :(得分:0)

通过修改this.events对象中的事件处理程序,事件处理程序不再相同。

http://jsfiddle.net/asXzA/1/

我建议您创建一个通过this.events系统添加的事件注册表,这样您就可以轻松地将内容输出。

this.events = {
    eventRegistry : {},

    addEventListener : function(element, eventName, eventHandler, scope) {
        var scopedEventHandler = scope ? function(e) { eventHandler.apply(scope, [e]); } : eventHandler;

        // save the scoped event handler
        if (typeof eventRegistry == "undefined")                
            eventRegistry = {};

        if (typeof eventRegistry[eventName] == "undefined")
            eventRegistry[eventName] = {};

        eventRegistry[eventName][eventHandler] = scopedEventHandler;

        if(document.addEventListener)
            element.addEventListener(eventName, scopedEventHandler, false);
        else if(document.attachEvent)
            element.attachEvent("on"+eventName, scopedEventHandler);
    },

    removeEventListener : function(element, eventName, eventHandler, scope) {

        // retrieve saved event handler
        var scopedEventHandler = eventRegistry[eventName][eventHandler];

        if(document.removeEventListener)
            element.removeEventListener(eventName, scopedEventHandler, false);
        else if(document.detachEvent)
            element.detachEvent("on"+eventName, scopedEventHandler);
    }
};

this.keyEvent = function () { alert("keypressed"); this.events.removeEventListener(document.body, "keydown", this.keyEvent, this); alert("removed"); };
this.events.addEventListener( document.body, "keydown", this.keyEvent, this);​