避免多次添加事件 [英] Avoid Adding Event Multiple Times
问题描述
我正在将使用addEvent("keydown", function() {});
的事件动态添加到元素中.我的问题是,有时在同一元素上两次或多次运行此代码.由于为该事件注册的函数运行了几次,因此行为变得笨拙.
I am dynamically adding events using addEvent("keydown", function() {});
to an element. My problem is that there are times when this code get's run on the same element twice or more. The behavior becomes clunky as the function registered for that event runs a couple of times.
有没有办法让我在一个元素上只运行一次上面的代码?也许检查事件是否已经添加过?
Is there a way for me to only run the code above only once on an element? Maybe check if the event has already been added before?
推荐答案
要么不要每次都使用新函数,要么不要使用类或某些东西来告诉您已添加它.
Either don't use a new function each time, or use a class or something to tell you you've added it.
MooTools的addEvent
是addEventListener
/attachEvent
上的一个相当薄的包装器,它不会两次添加相同的功能.因此,如果确保使用相同的功能,则可以再次调用addEvent
而无需执行任何操作:
MooTools' addEvent
is a fairly thin wrapper on addEventListener
/attachEvent
, which won't add the same function twice. So if you ensure you're using the same function, you can call addEvent
again without it doing anything:
// Somewhere it's created **once**
function keyDownHandler() {
// ....
}
然后:
element.addEvent("keydown", keyDownHandler); // Adds it only if not there
实时示例:
addIt();
addIt();
function addIt() {
$("foo").addEvent("click", handler);
}
function handler() {
var p = document.createElement('p');
p.innerHTML = new Date();
document.body.appendChild(p);
}
<div id="foo">Click me</div>
<script src="https://ajax.googleapis.com/ajax/libs/mootools/1.5.0/mootools-yui-compressed.js"></script>
if (!element.hasClass("keydown-handler")) {
element.addClass("keydown-handler").addEvent("keydown", function() { /*...*/});
}
实时示例:
addIt();
addIt();
function addIt() {
var element = $("foo");
if (!element.hasClass("click-handler")) {
element.addClass("click-handler").addEvent(
"click",
function() {
var p = document.createElement('p');
p.innerHTML = new Date();
document.body.appendChild(p);
}
);
}
}
<div id="foo">Click me</div>
<script src="https://ajax.googleapis.com/ajax/libs/mootools/1.5.0/mootools-yui-compressed.js"></script>
这篇关于避免多次添加事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!