删除绑定到处理程序的jQuery事件(Remove jQuery event where this is bound to the handler)
我试图删除一个jQuery事件谁回调绑定了this 。 问题是.bind()每次创建一个新函数...所以当我尝试删除事件时,它在技术上不是相同的功能,所以它不起作用。
在这种情况下,我无法弄清楚如何在回调中保持正确:
class Controller { open() { $('body').on('click', this.handleClick.bind(this)); } close() { $('body').off('click', this.handleClick.bind(this)); } }I am trying to remove a jQuery event who's callback is bound with this. The problem is that .bind() creates a new function every time... so when I try removing the event, it is technically not the same function so it doesn't work.
I can't figure out how to keep the right this inside the callback in this case:
class Controller { open() { $('body').on('click', this.handleClick.bind(this)); } close() { $('body').off('click', this.handleClick.bind(this)); } }最满意答案
您可以简单地使用jQuery名称空间:
class Controller { open() { $('body').on('click.myNamespace', this.handleClick.bind(this)); } close() { $('body').off('click.myNamespace'); } }You can simply use jQuery namespaces:
class Controller { open() { $('body').on('click.myNamespace', this.handleClick.bind(this)); } close() { $('body').off('click.myNamespace'); } }更多推荐
发布评论