在Backbone.js中存储获取的用户信息

时间:2014-01-10 06:26:43

标签: javascript backbone.js fetch

我有一个模型“用户”调用一个带有ID的API,返回所需的分页,语言,角色等信息。

当我对模型的实例执行提取时,它工作正常。我知道我需要等待获取完成,但是如何保留我可能在成功回调中定义的变量对应用程序的其余部分可见?

var user = new App.Models.User();

user.fetch().done(function() {
    //when I define fruit_list here, it's not visible to the outside world
});

// fruit_list view uses the information retrieved from the user model (pagination), which falls into the default because fetch wasn't performed yet

var fruit_list = new App.Views.FruitList();

有什么想法?存储全局用户信息的最佳做法是什么?

非常感谢!

1 个答案:

答案 0 :(得分:0)

如果您关心外部世界的可见性,这可以是一种选择。

您已经为您的应用程序声明了一个全局变量App。您也可以为modelview实例创建单独的命名空间。例如,

App.models = {
    user : new App.Models.User()
};
App.views = {
    fruit_list : new App.Views.FruitList()
};
App.models.user.fetch().done(function() {
    // do your stuff with 'user' model and 'fruit_list' view
    // App.views.fruit_list
});