开发者

jQuery keyup delay event

开发者 https://www.devze.com 2022-12-21 14:16 出处:网络
I\'m trying to creat special event for jQuery. I want to make controled delay, which will work when user stops fo 0.5s. But I can\'t use setTimeout.

I'm trying to creat special event for jQuery. I want to make controled delay, which will work when user stops fo 0.5s. But I can't use setTimeout.

jQuery.event.special.keyupdelay = {
    add : function(handler, data, namespaces) {
        var delay = data && data.delay || 100;

        return function(event) {                                                
            setTimeout(function() { handler.apply(this, arguments);}, data);
        }
    },

    setup: function(data, namespaces) {
        jQuery(this).bind("keyup", jQuery.event.special.keyupdelay.handler);
    },

    teardown: function(namespaces) {
        jQuery(this).unbind("keyup", jQuery.event.special.keyupdelay.handler);        
    },

    handler: function(event) {              
        event.type = "keyupdelay";
        jQuery.event.handle.apply(this, arguments);
    }
};

To use it like this

$(".money").bind("keyupdelay", {delay: 1000}, function( event ) {
    alert('Delayed!');
});  

setTimeout not working.

I can make it like this

var timer;

$(".quantity input").keyup(function() {
        var self = $(this);

        if(timer) {
            clearTimeout(timer);
            timer = null;
        }
        timer = setTimeout( function() {
            var qty = self.val();
            $(".qty").html(开发者_如何学运维qty);
        }, 300);
});

But I want to create special event, which triggers with delay. I have a lot of controls which have to work with delay.


I'm guessing it might be your use of "this" in the timeout: When the function is ran after the delay, "this" will be the window object.

jQuery.event.special.keyupdelay = {
    add : function(handler, data, namespaces) {
        var delay = data && data.delay || 100,
            that = this;

        return function(event) {                                                
            setTimeout(function() { handler.apply(that, arguments);}, data);
        }
    },

    setup: function(data, namespaces) {
        jQuery(this).bind("keyup", jQuery.event.special.keyupdelay.handler);
    },

    teardown: function(namespaces) {
        jQuery(this).unbind("keyup", jQuery.event.special.keyupdelay.handler);        
    },

    handler: function(event) {              
        event.type = "keyupdelay";
        jQuery.event.handle.apply(this, arguments);
    }
};
0

精彩评论

暂无评论...
验证码 换一张
取 消