This is my code snippet of pure javscript method that i use on dom object wrappers to attach events with extra params.
/**
* Attach event listener.
* @param {string} eventName
* @param {function} handler
* @param {bool} useCapture
* @param {array} extraParams
*/
AbstractViewObject.prototype.on = function (eventName, handler, useCapture, extraParams) {
var self = this;
var name = eventName + '-' + handler.name;
var obj = {};
if (typeof handler.name === 'undefined') {
throw new Error('Can\'t register an anoymous function as handler!');
}
obj[name] = function (e) {
var params = [e];
if (Array.isArray(extraParams) && extraParams.length > 0) {
params = params.concat(extraParams);
}
handler.apply(self, params);
};
this.eventsMap[name] = obj[name];
this.dom.addEventListener(eventName, obj[name], useCapture);
};
/**
* Remove event listener.
* @param {string} eventName
* @param {function} handler
*/
AbstractViewObject.prototype.off = function (eventName, handler) {
var name = eventName + '-' + handler.name;
if (this.eventsMap[name]) {
this.dom.removeEventListener(eventName, this.eventsMap[name]);
this.eventsMap[name] = null;
}
else {
throw new Error('This object doesn\'t posses such handler. Event: ' + eventName + '. Handler: ' + handler.name);
}
};
This code forces named based function handlers to help sustain references to functions in case on removing them.
This is why you could have problems with removeEventHandler. If you add anoymous function as a handler you can remove it only by passing reference to the same function. So you have to keep it in some var that will latter be used in removal.