简体   繁体   English

有没有一种方法可以在jQuery中创建延迟的对象包装器

[英]Is there a way to create a deferred object wrapper in jQuery

I've been reading a lot about the new jQuery.Deferred object. 我已经阅读了很多有关新的jQuery.Deferred对象的信息。 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. 有一两件事,会是真正有用的将是能够将现有对象转换为递延之一,那么你会得到关于你来自哪里,让您的数据100%的灵活性。

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. 您无需包装对象即可获得此效果,因为大多数将promise作为参数传递的方法会将普通对象视为已解决的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) . 这至少可以让您处理要调用promise方法例如, my_promise.done()而不是传递 promise的情况,即$.when(my_promise)

[untested, may not work, E&OE, etc.] [未经测试,可能无法正常运行,E&OE等。]

EDIT 编辑

Actually, I thnk all you have to do is wrap your plain-old-data in $.when : 实际上,我想您要做的就是将原始数据包装在$.when

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM