简体   繁体   中英

How to make hammerjs events fire only once?

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');
});

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/

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM