javascript - jQuery : deferred/promise

标签 javascript backbone.js

我正在尝试从示例应用程序中找出主干(请参阅 https://github.com/elfsternberg/The-Backbone-Store )。该代码使用 jQuery 的 Deferred 和 Promise(),如下面的代码所示。我已阅读有关 jQuery 的文档,但无法从下面的示例中弄清楚如何使用这些方法。您可能需要更多代码来回答这个问题,但也可能不需要。这些是我对此的疑问

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

2) 返回promise.promise();会发生什么?是调用Deferred方法吗?什么时候?为什么要这样做?这似乎是一种递归方法?

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) is dfd.resolve called once fadeOut is done? if so, what does dfd.resolve trigger?

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

2) What is happening by returning promise.promise(); is it calling the Deferred method? when? why is it done this way? this seems like a recursive method?

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

3) is it possible that dfd.resolve is triggering other methods not shown in this code?

是的。 Deferred 只不过是一个允许您注册回调的对象。调用.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!'

});

关于javascript - jQuery : deferred/promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12658641/

相关文章:

backbone.js - RequireJS - 我是否必须为子类重新导入以前需要的文件

forms - Backbone.js 和表单输入模糊

javascript - 如何防止Javascript执行导致页面因大量HTML而无响应?

javascript - 如何对数组进行排序,但排除某些元素(保持在数组中的相同位置)

javascript - 从一个 HTML 页面中取出一个 <div> 并显示在另一个页面的弹出窗口中?

javascript - Marionette document.querySelector ('#test' ) 返回 null 但这样做。$ ('#test' ) 不会

javascript - jquery/underscore/backbone/parse 模块的 Require.js 加载超时

javascript - 使用 jQuery 在容器下单击事件

javascript - Chrome.webrequest.onBeforeRequest 多次调用自身

backbone.js - Backbone 模型 ID 是否需要是数字?