Directly upload the code
ele.addEventListener('click', function(e) {
console.log(e)
})
Here I need to unbind ele's click event under certain circumstances, but I need to use additional parameters such as event when binding. How should I unbind?
I know that removeEventListener can be unbound, but the function they want to pass in must be the same named external function, which doesn't work if I need parameters
I also know that when you only need to bind a click event, use ele.click = function() {} and then use ele.click = null to unbind, or use the methods provided by other tool libraries.
But now I just want to know if it is possible to use removeEventListener to cancel it
Thanks
淡淡烟草味2017-07-05 10:40:23
That’s ok, as long as the binding and unbinding functions point to the same one
function handler(e){
//操作
console.log(e)
}
ele.addEventListener('click', handler);//绑定
ele.removeEventListener('click', handler);//解绑
高洛峰2017-07-05 10:40:23
function bindFunc(e) {
console.log(e);
//用参数e来进行一些操作,干啥都行
}
this.cusBindFunc = bindFunc.bind(this, e); //bind一下,因为remove的时候用的func必须和绑定的时候一样
ele.addEventListener('click', this.cusBindFunc);//绑定事件
ele.removeEventListener('click', this.cusBindFunc);//解绑
In addition, for compatibility, it can be compatible with attachEvent and detachEvent
Not sure if I understand your question @AugustEchoStone