按变量JS removeEventListener

时间:2015-11-13 15:45:17

标签: javascript

我试图通用订阅和取消订阅活动。因此我想知道,是否有可能将事件监听器存储到变量中,然后通过变量引用解除绑定

// AddEventListener
var listener = function() {console.log("listener");};
var listener_reference = window.addEventListener("message", my_function );

// RemoveEventListener
window.removeEventListener(listener_reference); 
// or
listener_reference.removeEventListener();

DO 知道如何以经典方式订阅和取消订阅活动,例如正如MDN所述,但我正在通过将侦听器分配给变量来寻找一种方法。因此,这种经典方式不是我的问题的答案

var div = document.getElementById('div');
var listener = function (event) {
  /* do something here */
};
div.addEventListener('click', listener, false);
div.removeEventListener('click', listener, false);

我努力建立两个原型EventListener和EventManager:

function EventListener (obj, eventtype, listener, useCapture) {
    this.obj = obj;
    this.eventtype = eventtype;
    this.listener = listener;
    this.useCapture = useCapture || false;

    this.removeEventListener = function () {
        console.log("remove",this);
        this.obj.removeEventListener(this.eventtype,this.listener,this.useCapture);
    }
    this.obj.addEventListener(this.eventtype, this.listener, this.useCapture)
};

function EventManager() {

    var eventlisteners=[];

    this.addEventListener = function (obj, eventtype, listener, useCapture) {
        var eventlistener = new EventListener(obj, eventtype, listener, useCapture);
        eventlisteners.push(eventlistener);
        return eventlistener;
    };
    this.removeAllEventListeners = function () {
        for (var i = 0; i < eventlisteners.length; i++) {
            if(eventlisteners[i] instanceof EventListener ) {
                eventlisteners[i].removeEventListener();
                delete eventlisteners[i];
            }
        }
    };
}



var listener = function(){console.log("Hello World!")};
var clicks = new EventListener(window,"click",listener);
clicks.removeEventListener();

var manager = new EventManager();
var listener2 = function(){console.log("Hello World 2!")};
var clicks2 = manager.addEventListener(window,"click",listener);
manager.removeAllEventListeners();

0 个答案:

没有答案