开发者

How to get a Boolean return value from jQuery trigger method?

I have a custom event that I want to fire using jQuery's trigger method:

$(wiza开发者_JAVA百科rd).trigger('validatingStepValues');

Then in the wizard's current step code, I subscribe to this event as follow:

$(wizard).bind('validatingStepValues', function (){
    // Validating step's form data here; returning false on invalid state.
});

Then in my wizard, again I want to be able to stop user from going to the next step, if a false value is returned from validation process? I'd like to have something like:

$(wizard).trigger('validatingStepValues', validReturnCallback, invalidReturnCallback)


Have you considered using something like:

function wizardValidator(successCallback, failureCallback) {
    return function() {

        // Validating step's form data here;

        if (wasValid && successCallback) {
            successCallback();
        } 
        else if (! wasValid && failureCallback) {
            failureCallback();
        }

        return wasValid;
    };
}

$(wizard).bind('validatingStepValues', wizardValidator(validReturnCallback, invalidReturnCallback));

This requires that you know the callbacks that you want to use at the time you bind the event listener. If you want to be able to use different callback functions at different times, you could define additional event types, like:

$(wizard).bind('validatingStep2Values', wizardValidator(validStep2ReturnCallback, invalidStep2ReturnCallback));
$(wizard).bind('validatingStep3Values', wizardValidator(validStep3ReturnCallback, invalidStep3ReturnCallback));

Alternately, events that you create by calling trigger() propagate up the DOM hierarchy. Returning false an event handler cancels this propagation. So you could bind your desired success callback function as an event listener on your wizard's parent node. That won't do anything to allow your failure callback to be executed, however.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜