简体   繁体   中英

unbind all in event string using jQuery one()

I am checking for any interaction using JQuery's .one() function.

    var myEvents = 'mousedown mousemove mouseup touchstart touchmove touchend mouseout';

    jQuery(document).one(myEvents, function(){
        //do something only once.
});

But I would like all these to be ubinded once any of these events has fired. I know I can unbind again with jQuery(document).unbind(myEvents) , but was wondering if there was a clean inbuilt way of simply unbinding after one event.

EDIT: Here is a fiddle: http://jsfiddle.net/4HkQy/6/

You could extend jQuery with a function which serves exactly that purpose.

jQuery.fn.extend({
    oneForAll: function(events, handler) {
        var that = this,
            oneForAll = function() {
                that.unbind(events, oneForAll);
                handler.apply(this, arguments);
            };

        that.on(events, oneForAll); 
    }
});

You would use it exactly the way you used one it would just be oneForAll .

JSFiddle: Demo

use .off()

jQuery(document).one('mousedown mousemove mouseup touchstart touchmove touchend mouseout', function (event) {
    console.log(event.originalEvent.type);
    jQuery('p').append(event.originalEvent.type);
    //remove all handlers
    jQuery(document).off('mousedown mousemove mouseup touchstart touchmove touchend mouseout');
});

But i would recommend using a namespaced handlers so that you won't remove any other event handlers by mistake.

jQuery(document).one('mousedown.myonce mousemove.myonce mouseup.myonce touchstart.myonce touchmove.myonce touchend.myonce mouseout.myonce', function (event) {
    console.log(event.originalEvent.type);
    jQuery('p').append(event.originalEvent.type);
    //remove all handlers
    jQuery(document).off('.myonce');
});

Demo: Fiddle

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