Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将绑定函数绑定到事件并解除绑定_Javascript_Event Handling_Dom Events_Underscore.js_Bind - Fatal编程技术网

Javascript 将绑定函数绑定到事件并解除绑定

Javascript 将绑定函数绑定到事件并解除绑定,javascript,event-handling,dom-events,underscore.js,bind,Javascript,Event Handling,Dom Events,Underscore.js,Bind,我在应用程序中使用as消息总线内部。现在我需要绑定和解除绑定一些事件处理程序。由于我希望它们也能在给定的上下文中使用,因此我最终使用以下语法: messageBus.on('foo::bar', _.bind(eventHandler, this)); 问题是我需要在以后的某个时间点解开它们,所以我写道: messageBus.off('foo::bar', _.bind(eventHandler, this)); 不幸的是,这不起作用,因为每次\uu0.bind都会返回包装器函数的一个新实

我在应用程序中使用as消息总线内部。现在我需要绑定和解除绑定一些事件处理程序。由于我希望它们也能在给定的上下文中使用,因此我最终使用以下语法:

messageBus.on('foo::bar', _.bind(eventHandler, this));
问题是我需要在以后的某个时间点解开它们,所以我写道:

messageBus.off('foo::bar', _.bind(eventHandler, this));
不幸的是,这不起作用,因为每次
\uu0.bind
都会返回包装器函数的一个新实例。现在,我当然可以运行一次
。.bind
并绑定包装的函数,例如:

var fn = _.bind(eventHandler, this);
messageBus.on('foo::bar', fn);
messageBus.off('foo::bar', fn);
这工作得非常好,但是如果您有一些事件处理程序,代码很快就会变得不那么可读


如果不需要外部化对
bind
函数的调用,您如何解决这个问题?如果您多次调用包装器,并且函数和上下文都相同,是否有一个始终返回相同包装器的替代函数?

underline.js仅为此用例提供了一个
bindAll
方法,来自:

绑定由MethodName指定的对象上的许多方法,以便在调用这些方法时在该对象的上下文中运行

否则,您可以使用一个闭包,该闭包在调用时始终返回相同的绑定函数,即:

function getOrCreateBoundEventHandlerFor(eventType, callback) { 

    // Initialise the handler map if it's not already been created.
    this._boundEventHandlerMap = this._boundEventHandlerMap || {};

    // If no handler was mapped, create a new one.
    if (this._boundEventHandlerMap[eventType] === void 0) {
        this._boundEventHandlerMap[eventType] = _.bind(callback, this);
    }

    return this._boundEventHandlerMap[eventType];
}