0

So I want to call a function and pass it parameters on a click event using vanilla javascript (which I've done) but I'm having a problem with detaching the event afterward. When the click event is fired I want to call a function and pass it parameters including the event object and then detach the event. I've tried a few things but the problem I'm running into is that the anonymous function can't be referenced after calling it so I can't pass it as a parameter to the event "unhandler". How can I capture the touch event while also passing parameters the the callback?

function bindClickExpandEvent(element, type, handler, obj) {
    if (element.addEventListener) {
        element.addEventListener(type, function (event) {
            handler(event, obj);
        }, false);
    } else {
        element.attachEvent('on' + type, function (event) {
            handler(event, obj);
        });
    }
}

function removeClickExpandEvent(elem, eventType, handler) {
    if (elem.removeEventListener)
        elem.removeEventListener(eventType, handler);
    if (elem.detachEvent)
        elem.detachEvent('on' + eventType, handler);
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Craig Lafferty
  • 771
  • 3
  • 10
  • 31
  • If you are using jQuery at all, you could use this http://api.jquery.com/one/ – Seano666 Jun 03 '14 at 17:19
  • 1
    This might help: [How to removeEventListener that is addEventListener with anonymous function?](http://stackoverflow.com/q/5660131/218196). The problem is that you can't unbind the event handler since you don't have a reference to the function you bound. – Felix Kling Jun 03 '14 at 17:21

1 Answers1

0

If you always want to immediately detach the listener after the event has fired, you can do that directly from the handler where you do have a reference to it:

function bindClickExpandEventOnce(element, type, handler, obj) {
    function boundhandler(event) {
        removeClickExpandEvent(element, eventType, boundhandler);
        handler(event, obj);
    }
    if (element.addEventListener)
        element.addEventListener(type, boundhandler, false);
    else
        element.attachEvent('on' + type, boundhandler);
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375