$。当不等待Ajax请求完成时

时间:2014-01-28 12:39:05

标签: javascript jquery ajax backbone.js .when

我想首先使用Backbone.js呈现一个视图,该视图显示从服务器中提取的文章。然后,我想将此标记为“已查看”,并将未看到的消息计数返回给路由器,因为它需要可供其他视图使用。

所以在我的路由器中,我有:

    getArticle: function (id) {

        require(["app/models/article", "app/views/Article"], function (models, Article) {

                var article = new models.Article({id: id});

                article.fetch({
                    success: function (data) {

                        var articleView = new Article({model: data, message_count:that.message_count});

                        slider.slidePage(articleView.$el);

                        $.when(articleView.saveView()).done(function(data){
                            console.log('in when and data is ');
                            console.log(data);
                        });

                    },
                    error: function(){
                        console.log('failed to fecth artcie'); 
                    }
                });

        });
    },
文章视图中的

saveView()是:

    saveView: function(){

        var viewDetails = [];

        viewDetails.device_id = this.options.device_id;
        viewDetails.article_id = this.model.id;
        viewDetails.project_title = project_title;

        var article_view = new models.ArticleView();

        article_view.save(viewDetails, 
                        {
                        success: function(data) {
                                var count = data.get('count');   
                                console.log('in saveView() success and count is ');
                                console.log(count); 
                                return count;     
                            },
                            error:   function(model, xhr, options){
                               console.log(xhr.responseText);
                            },
                        });
    },

这会命中REST API,记录文章的查看,然后返回一些看不见的文章。这导致控制台输出:

  

在何时和数据是router.js:286 undefined router.js:287 in   saveView()的成功和计数是Article.js:45 4

因此,不知何故,$.when无效,因为它不会在执行.done脚本之前等待Ajax请求发送。有任何想法吗?

1 个答案:

答案 0 :(得分:1)

您需要返回$.when的jQuery Deferred对象才能正常工作:

return article_view.save(viewDetails, 
    {
    success: function(data) {
            var count = data.get('count');   
            console.log('in saveView() success and count is ');
            console.log(count); 
            return count;     
        },
        error:   function(model, xhr, options){
           console.log(xhr.responseText);
        },
    });

Backbone' save()方法returns a jqXHR object,其行为与Deferred对象的行为方式相同。如上所述,只需将回复链接起来。这应该$.when()等待请求完成。