views:

719

answers:

1

Hi, 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.

A: 

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