在不同的obj属性中设置延迟/保证

时间:2014-05-01 22:24:52

标签: javascript jquery

使用jquery 1.6。*

我正在使用模块的模式。我希望能够在我的'UNI.obj1'中创建和解决deffered,并能够使用它们,这样我就可以在我的“UNI.obj2”对象中启动行为。

假设我有以下对象:

var UNI = {};

UNI.obj1 = function() {
    // set up a deferred here;

    var method1 = function(){
       // RESOLVE deferred here

    }
    var method1A = function(){
        window.onload = function(){ 
            method1(); 
        }
    }()
}()

UNI.obj2 = function(o) {
    var method2 = function(){
       // Use the PROMISE of the resolve here

    }
}(UNI.obj1);

2 个答案:

答案 0 :(得分:1)

定义您的延期对象并返回它的承诺,然后对其采取行动。

var UNI = {};

UNI.obj1 = function () {
    // set up a deferred here;
    var def = $.Deferred();

    var method1 = function () {
        // RESOLVE deferred here
        def.resolve();

        return def.promise();
    }
    var method1A = function () {
        window.onload = function () {
            method1();
        }
    }()
    return def.promise();
}

UNI.obj2 = function (o) {
    var method2 = function () {
        // Use the PROMISE of the resolve here
        o().done(function () {
            // it was resolved!
            console.log("Resolved!");
        });
    }()
}(UNI.obj1);

答案 1 :(得分:1)

var UNI = {};

UNI.obj1 = function() {
    // set up a deferred here;
    var deferred = new $.Deferred();

    var method1 = function(){
       // RESOLVE deferred here
       deferred.resolve('something')
    }
}

UNI.obj2 = function(o) {
    var method2 = function(promise){
       // Use the PROMISE of the DEFERRED? here
       // pass promise
    }
}

但我没有在你的问题中看到你想如何传递延迟对象,因为你说你想要模块模式,你可以:

UNI.obj1 = function() {
    // set up a deferred here;
    var deferred = new $.Deferred();

    var method1 = function(){
       // RESOLVE deferred here
       deferred.resolve('something')
    }

    // module pattern
    return {
      promise: deferred.promise()
    };
    // you could also just return the promise, maybe I am misunderstanding your question
    // return deferred.promise();
}

UNI.obj2 = function(o) {
    var method2 = function(promise){
       // Use the PROMISE of the DEFERRED? here
       // pass promise
    }

    // module pattern
    return {method2: method2};
}


// Usage
var o1 = UNI.obj1();
var o2 = UNI.obj2();
o2.method2(o1.promise);