Ching Ching Ching Ching - 3 months ago 18
Javascript Question

Jquery ONE function PURE js

there! i have a problem when creating

one
function just like
JQUERY
does.

here is the action : https://jsfiddle.net/77yzLt6v/

one time execution event

HTML :

<div id="justOnce">click me!</div>

function one(dom, event, callback) {
dom.addEventListener(event, function(e) { // add event
this.removeEventListener(event, callback); // remove it
});

}
one(document.getElementById("justOnce"), "click", function() {

alert("this alert only show once time");

});


what's wrong with my code?

thanks in advance...

Answer

Your code binds an event handler that removes callback as an event handler.

The only problem is … you never bound callback as an event handler in the first place.

You want something more like this:

function one(dom, event, callback) {
    function handler(e) {
        callback.call(this, e);
        this.removeEventListener(event, handler);
    }
    dom.addEventListener(event, handler); 
}    

i.e.

  • You need to call the callback
  • You need to remove the event handler you actually bound
Comments