javascript - About binding and unbinding of js native events
巴扎黑
巴扎黑 2017-07-05 10:38:23
0
2
686

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

巴扎黑
巴扎黑

reply all(2)
淡淡烟草味

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);//解绑
小葫芦
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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template