How do I disable and then re-enable a Hammer Event properly using Hammer.js?

1.1k views Asked by At

I'm using hammer.js and jquery.hammer.js in order to handle multiple different types of events (mostly tap events).

I made a wrapper function to be used for any/all tap event listener declarations. This is the function.

var OnClick = function(button, CallbackFunction, TurnBackOnAfterStartCallback)
{
    if(TurnBackOnAfterStartCallback != false)
    {
        TurnBackOnAfterStartCallback = true;
    }

    if(!button)
    {
        LogResult("Error: Attempted to create Hammer Click Event Listener without assigning a jQuery Object to listen too...");
        return;
    }

    if(!CallbackFunction)
    {
        LogResult("Error: Attempted to create Hammer Click Event Listener without assigning a Callback Function...");
        return;
    }


    $(button).hammer().on("tap", function(event)
    {
        var target = event.target;

        // Disable the button so that we can't spam the event....
        $(target).hammer().off("tap");

        // We receive the event Object, incase we need it...
        // Then we call our CallBackFunction...
        if(CallbackFunction)
        {
            CallbackFunction(target);
        }

        // Renable the button for future use if need be.
        if(TurnBackOnAfterStartCallback)
        {
            $(target).hammer().on("tap", CallbackFunction);
        }
    });
};

When I register an event using this function it works as expected. First it disables the event listener so you can't spam the event by clicking the button 100 times... Like so...

$(target).hammer().off("tap");

Then it preforms any callback functionality if there exists any...

if(CallbackFunction)
{
    CallbackFunction(target);
}

Finally we re-enable the button for future use, unless we've specified that it will not be turned back on...

// Renable the button for future use if need be.
if(TurnBackOnAfterStartCallback)
{
    $(target).hammer().on("tap", CallbackFunction);
}

This works perfectly during the first event launch... However, once I trigger the event again the Callback function is sent the event and not the event.target for some reason...

If I remove the .off and .on calls then it works as expected but can be spammed...

For a live example checkout this jsfiddle... It prints the result to the console... The first output is correct, everything after that isn't as expected. https://jsfiddle.net/xupd7nL1/12/

1

There are 1 answers

0
Ricky On

Never mind, I had a dumb moment there...

The issue was that I was calling the event listener directly and not through my wrapper function, OnClick...

In other words change...

if(TurnBackOnAfterStartCallback)
{
    $(target).hammer().on("tap", CallbackFunction);
}

to

if(TurnBackOnAfterStartCallback)
{
    OnClick(target, CallbackFunction, TurnBackOnAfterStartCallback);
}