javascript - Avoid Adding Event Multiple Times -
i dynamically adding events using addevent("keydown", function() {});
element. problem there times when code get's run on same element twice or more. behavior becomes clunky function registered event runs couple of times.
is there way me run code above once on element? maybe check if event has been added before?
thanks helps.
either don't use new function each time, or use class or tell you've added it.
not using new function each time
mootools' addevent
thin wrapper on addeventlistener
/attachevent
, won't add same function twice. if ensure you're using same function, can call addevent
again without doing anything:
// somewhere it's created **once** function keydownhandler() { // .... }
then:
element.addevent("keydown", keydownhandler); // adds 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>
Comments
Post a Comment