Sunday, February 20, 2011

jQuery plugin executes a callback based on a condition

    There is a Jquery utility that provides a way to execute callback functions based on one or more objects named jQuery.when(). However, when you need to do the same thing but based on one or more "conditions", how can you archive this?
    For example, you have a javascript interger. What you want to do is watching it's value and wait until the value matchs the expected value then you will execute a function. The value of this variable can be changed in various ways depend on users's activities.
    I know that we can simply work around this by checking that variable in the callback functions of jquery events like button clicked, textbox changed. But let's imagine you have alot of event that can change the value of that interger, in this case I don't wish to do that way. I did research on the Internet to find a proper solution but unfortunately, I had to make a solution myself. Personally, It's like a little cheat but I couldn't find any better way so I'm very grateful if someone suggests a better method.
Here is the supper simple implementation:

$.waitUntil = function (delegate, action, timeOutObj) {
    function _waitUntil(params) {
        $.waitUntil(params.condition, params.action, params.timeOutObj);
    }

    if (delegate.apply() == true) {
        action.apply();
    }
    else {
        if (timeOutObj != null) {
            clearTimeout(timeOutObj);
        }
        var param = { condition: delegate, action: action };
        param.timeOutObj = setTimeout(_waitUntil, 100, param);
    }
};

And here is the code sample:
var watchedItem = 0;
$.waitUntil(
    function() {
        return watchedItem > 2;
    },
    function() {
        alert('You have clicked 3 times');
    },
    null
);

Demo: Click to see the demo

0 comments:

Post a Comment