1

I'm using the latest build of hammerjs (1.0.6). The jquery build they have is a bit buggy with requirejs, so I'm just using the standard build.

Fiddle: http://jsfiddle.net/mcfarljw/fDYx3/

How can I get this tap event to fire once and then remove itself? I thought it would have been as simple as calling off, but that appears not to be the case. Any help would be greatly appreciated!

var tapCount = 0;
Hammer($('#box')[0]).on('tap', function() {
    tapCount++
    $('#counter').text(tapCount);
    Hammer($('#box')[0]).off('tap');
});
4
  • Then you just want to let the user tap just one time, right?
    – Hackerman
    Commented Jan 23, 2014 at 20:43
  • Use .one() method instead of .on().
    – Ram
    Commented Jan 23, 2014 at 20:44
  • Yes, I'd like it to fire once and then remove itself. @BlackSheep, this isn't jquery so there is no one method.
    – Joshua
    Commented Jan 23, 2014 at 20:51
  • Hammer has a jQuery version.
    – Ram
    Commented Jan 23, 2014 at 23:46

2 Answers 2

0

You can try this:

var tapCount = 0;
var callback = function() {
tapCount++
$('#counter').text(tapCount);
Hammer($('#box')[0]).off('tap',callback);
};
Hammer($('#box')[0]).on('tap', callback );

Working fiddle: http://jsfiddle.net/robertrozas/EuSK4/

2
  • So it looks like the event can't be removed until it has officially completed firing? Or rather it needs to be able to reference the callback function.
    – Joshua
    Commented Jan 23, 2014 at 20:54
  • It needs to reference the callback function, because if you call it this way: Hammer($('#box')[0]).on('tap'); it's the same as: Hammer($('#box')[0]).on('tap', undefined );
    – Hackerman
    Commented Jan 23, 2014 at 20:59
0

To fire the event only once, you need to store the reference to the manager instance that binds the event & use the same instance to unbind it.

http://jsfiddle.net/a8f1p6pt/3/

var hInstance ;
var handler = function() {
    alert('Alert Once');
    hInstance.off('tap', handler);
};
hInstance = Hammer($('#box')[0]);
hInstance.on('tap', handler );

Not the answer you're looking for? Browse other questions tagged or ask your own question.