gpt4 book ai didi

javascript - 解绑匿名函数

转载 作者:数据小太阳 更新时间:2023-10-29 06:07:53 25 4
gpt4 key购买 nike

有人能告诉我如何“解除绑定(bind)”一个匿名函数吗?在 jQuery 中,它能够做到这一点,但我如何才能在我自己的脚本中实现这个功能。

这是场景:

以下代码将 onclick 事件附加到以 someDivId 作为 ID 的 Div,现在当您单击 DIV 时,它会显示“clicked!”。

var a  = document.getElementById('someDivId');
bindEvent(a,'click',function(){alert('clicked!');});

太好了,问题是如果函数是匿名的,如何将函数“取消附加”到 DIV,或者如何将所有附加事件“取消附加”到“a”元素?

unBind(a,'click'); //Not necessarily the given params, it's just an example.

这是 bindEvent 方法的代码:

function bindEvent (el,evtType,fn){
if ( el.attachEvent ) {
el['e'+evtType+fn] = fn;
el[evtType+fn] = function(){
fn.call(el,window.event);
}
el.attachEvent( 'on'+evtType, el[evtType+fn] );
} else {
el.addEventListener( evtType, fn, false );
}
}

最佳答案

最后,经过几个小时的测试和错误,我找到了一个解决方案,也许它不是最好的或最有效的,但......它有效! (在 IE9、Firefox 12、Chrome 18 上测试)

首先,我创建了两个跨浏览器和辅助的 addEvent() 和 removeEvent() 方法。 (灵感来自 Jquery 的源代码!)

HELPERS.removeEvent = document.removeEventListener ?
function( type, handle,el ) {
if ( el.removeEventListener ) {
//W3C Standard
el.removeEventListener( type, handle, true );
}
} :
function( type, handle,el ) {
if ( el.detachEvent ) {
//The IE way
el.detachEvent( 'on'+type, el[type+handle] );
el[type+handle] = null;
}
};

HELPERS.addEvent = document.addEventListener ?
function( type, handle,el ) {
if ( el.addEventListener ) {
//W3C Standard
el.addEventListener( type, handle, true );
}
} :
function( type, handle,el ) {
if ( el.attachEvent ) {
//The IE way
el['e'+type+handle] = handle;
el[type+handle] = function(){
handle.call(el,window.event);
};
el.attachEvent( 'on'+type, el[type+handle] );

}
}

我们还需要某种“容器”来存储元素的附加事件,如下所示:

HELPERS.EVTS = {};

最后是两个可调用和暴露给用户的方法:下一个添加事件(event)并将此事件关联到特定元素(el)的方法(处理程序)。

    function bindEvent(event, handler,el) {

if(!(el in HELPERS.EVT)) {
// HELPERS.EVT stores references to nodes
HELPERS.EVT[el] = {};
}

if(!(event in HELPERS.EVT[el])) {
// each entry contains another entry for each event type
HELPERS.EVT[el][event] = [];
}
// capture reference
HELPERS.EVT[el][event].push([handler, true]);
//Finally call the aux. Method
HELPERS.addEvent(event,handler,el);

return;

}

最后是取消附加特定元素 (el) 的每个预附加事件(事件)的方法

    function removeAllEvent(event,el) {

if(el in HELPERS.EVT) {
var handlers = HELPERS.EVT[el];
if(event in handlers) {
var eventHandlers = handlers[event];
for(var i = eventHandlers.length; i--;) {
var handler = eventHandlers[i];
HELPERS.removeEvent(event,handler[0],el);

}
}
}

return;

}

顺便说一句,要调用此方法,您必须执行以下操作:捕获一个 DOM 节点

    var a = document.getElementById('some_id');

使用相应的参数调用方法“bindEvent()”。

    bindEvent('click',function(){alert('say hi');},a);

并取消附加它:

    removeAllEvent('click',a);

就是这样,希望有一天对某人有用。

关于javascript - 解绑匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10254402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com