【问题标题】:using jquery's deferred with settimeout使用 jquery 的延迟与 settimeout
【发布时间】:2012-09-21 20:46:39
【问题描述】:

我有一个具有内部循环的模块(使用“settimeout”)。我想在每次计时器发生时触发一个回调。我尝试使用 jQuery 的延迟对象,但没有成功。类似:

 $(function(){
    var module = new MyModule();
    $.when(module.init()).then("DO Something");
 });

 function MyModule(){

    this.d = $.Deferred();

}

test.prototype.init = function(){
    clearTimeout(this.next);

    var self = this;

    /*  Do Something */

    self.d.resolve();

    this.next = setTimeout(function(){
        self.init(); /* The problem is here - internal call to self */
    }, 4000);
    return self.d.promise();
};

问题是计时器在内部调用该方法,所以我不会调用“.then(Do Something);”的主程序。我可以使用老式函数回调(将回调函数传递给模块),但我真的很想尝试这些很棒的功能。

谢谢,

亚尼夫

【问题讨论】:

    标签: javascript jquery jquery-deferred deferred


    【解决方案1】:

    延迟确实不是您想要的,因为这是一次性交易 - 您可能想要的是回调列表。

    jQuery 将其作为 $.Callbacks() 提供,这可能是您正在寻找的。​​p>

    function MyModule(){
    
        this._initCallbacks = $.Callbacks();
    
    }
    
    MyModule.prototype.onInit = function( cb ) {
        if ( typeof cb === "function" ) {
            this._initCallbacks.add( cb );
        }
    };
    
    MyModule.prototype.init = function(){
        clearTimeout( this.next );
    
        var self = this;
    
        this._callbacks.fire();
    
        this.next = setTimeout(function(){
            self.init();
        }, 4000);
    
        return this;
    };
    
    $(function(){
        var module = new MyModule();
    
        module.onInit(function() {
            console.log( "Do something" );
        });
    
        module.init();
    });
    

    JSFiddle:http://jsfiddle.net/SUsyj/

    【讨论】:

    • 很高兴知道这一点。就我而言,我只需要一个回调来处理所有调用,是不是有点矫枉过正?
    • 如果您只能保证有一个回调,那么它可能是。这取决于您的要求,以及您是否认为将来可能需要多个回调。
    猜你喜欢
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2022-08-02
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    相关资源
    最近更新 更多