jQuery:延迟/承诺

时间:2012-09-30 04:28:22

标签: javascript backbone.js

我试图从示例应用中找出主干(请参阅https://github.com/elfsternberg/The-Backbone-Store)。代码使用jQuery的Deferred和promise(),如下面的代码所示。我已经阅读了关于jQuery的文档,但我很难从下面的例子中找出如何使用这些方法。您可能需要更多代码来回答这个问题,但可能不是。这些是我的问题

1)dfd.resolve是否在fadeOut完成后调用?如果是这样,dfd.resolve会触发什么?

2)返回promise.promise()会发生什么?是调用延迟方法吗?什么时候?为什么这样做?这看起来像一个递归方法?

3)dfd.resolve是否可能触发此代码中未显示的其他方法?

      hide: function() {
            if ((":visible") === false) {

                return null;

            }
            promise = $.Deferred(_.bind(function(dfd) { 
                this.el.fadeOut('fast', dfd.resolve)}, this));
            return promise.promise();
        },

        show: function() {
            if (this.el.is(':visible')) { 
                return;
            }       
            promise = $.Deferred(_.bind(function(dfd) { 
                console.log("in promise section of show in base view");
                this.el.fadeIn('fast', dfd.resolve) }, this))
            return promise.promise();
        }

1 个答案:

答案 0 :(得分:4)

  

1)dfd.resolve是否在fadeOut完成后调用?如果是的话,那是什么   dfd.resolve触发器?

是。 jQuery.fadeOut接收回调作为其中一个参数。动画完成后,它将执行回调。在这种情况下,它恰好是Deferred的解析方法。

  

2)返回promise.promise()会发生什么?它是在呼唤   延期方法?什么时候?为什么这样做?这似乎是一个   递归方法?

这里没有任何递归promise只是一个变量,它包含对创建的Deferred对象的引用。 promise()jQuery.Deferred上的一种方法,它返回Deferred的修改版本,不允许您修改其行为方式。因此承诺呼叫者可以确定它将始终以相同的方式执行。

  

3)dfd.resolve是否可能触发其他方法   如此代码所示?

是。延迟只不过是一个允许您注册回调的对象。在延期时拨打.resolve()会触发done handlers,而拨打.reject()会触发任何fail handlers

一个非常简短的例子可能如下所示:

//A Deferred takes in a function that will be passed a reference
// to the Deferred object. This allows you to resolve or reject
// it at some point in the future.
var promise = $.Deferred(function(def){

   setTimeout(function(){

      def.resolve('Five seconds have passed!');      

   }, 5000);

}).promise();

//This will only get executed when the
// underlying Deferred gets resolved
promise.done(function(msg){

   alert(msg); // Displays: 'Five seconds have passed!'

});