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开发者_如何学Go .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, e.g. my_promise.done()
, as opposed to passing the promise, i.e. $.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"})
精彩评论