简体   繁体   中英

Is there a way to create a deferred object wrapper in jQuery

I've been reading a lot about the new jQuery.Deferred object. One thing that'd be really useful would be to be able to convert an existing object into a deferred one, then you'd get 100% flexibility about where you get your data from.

I'm thinking something along the lines of

$.makeDeferred({property: "data"}) // returns an object with .promise() method, in resolved state, and that passes the original object as data/context to any callback function

Does anyone know if this method already exists, or how to go about creating one?

You shouldn't need to wrap your object to get this effect, since most methods that are passed promises as parameters will treat a plain object as an already-resolved promise.

That said, if you really want this, try this:

(function($) {
    $.makeDeferred = function() {
        var d = $.Deferred();
        d.resolve(arguments);
        return d.promise();
    };
))(jQuery);

This would at least allow you to also handle the case where you want to call a method of the promise, eg my_promise.done() , as opposed to passing the promise, ie $.when(my_promise) .

[untested, may not work, E&OE, etc.]

EDIT

Actually, I thnk all you have to do is wrap your plain-old-data in $.when :

$.when({property: "data"})

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