简体   繁体   English

骨干fetch()成功回调不起作用

[英]Backbone fetch() success callback doesn't work

In my app, there are different user accounts. 在我的应用中,有不同的用户帐户。 What I'm trying to do is, show a loader.gif till the time .fetch() is fetching the content from resource url + rendering the views and hide the loader when fetching is done. 我正在尝试做的是显示loader.gif直到.fetch()从资源url获取内容+呈现视图并在获取完成时隐藏loader

Now, when a user logs in, his list of TODO items is fetched by Todos.fetch and on success callback, loader.gif fades out. 现在,当用户登录时, Todos.fetch将获取他的TODO项列表,并在成功回调时将loader.gif淡出。

$("#app").hide();
$(".loader").show();
Todos.fetch({
    success: function(){
            $("#app").show();
            $(".loader").hide();
        }
});

This works fine for all user except those which have no Todo items. 这对于所有没有Todo项目的用户都适用。 For these users, success callback is not triggered and loader.gif stays. 对于这些用户,不会触发成功回调,并且loader.gif保持不变。 Is there any other way to hide the loader.gif ? 还有其他方法可以隐藏loader.gif吗?


It seems to me that success function is called only when even a single model is added to the collection. 在我看来,只有将单个模型添加到集合中时,才会调用success函数。 If there is nothing to add to the collection, success isn't called. 如果没有什么可添加到集合中,则不会success

BackboneJS fetch delegates to sync. BackboneJS获取委托进行同步。 sync returns a jqXHR object for your own use. sync返回一个jqXHR对象供您自己使用。

You could just: 您可以:

Todos.fetch({
    success: function(){
            $("#app").show();
            $(".loader").hide();
        }
}).always(function() { $(".loader").hide() });

You can read more about it in this blog post . 您可以在此博客文章中了解更多信息

Apart from that, make sure that your server returns a valid json when the collection is empty. 除此之外,请确保您的服务器在集合为空时返回有效的json。 If the response is not a valid json you will get a failure. 如果响应不是有效的json,则会失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM