Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  100] [ 1]  / answers: 1 / hits: 17496  / 9 Years ago, fri, may 15, 2015, 12:00:00

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?


More From » dom-events

 Answers
1

Either don't use a new function each time, or use a class or something to tell you you've added it.



Not using a new function each time



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() {
// ....
}


then:



element.addEvent(keydown, keyDownHandler);    // Adds it only if not there


Live Example:





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>





Remembering you've added it:



if (!element.hasClass(keydown-handler)) {
element.addClass(keydown-handler).addEvent(keydown, function() { /*...*/});
}


Live Example:





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>




[#66596] Wednesday, May 13, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raveno

Total Points: 453
Total Questions: 92
Total Answers: 92

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
raveno questions
;