【问题标题】:Collection fetch and model parse集合获取和模型解析
【发布时间】:2013-02-10 12:16:13
【问题描述】:

我在我的模型中覆盖函数 parse(),当数据库中的姓名或姓氏为空时,我正在询问 Facebook API:

var Friend = Backbone.Model.extend({ 
parse : function(response) {
    var self = response,
        that = this;

    if(!response.first_name) {
        FB.api('/'+response.fbid, function(response) { 
            self.first_name = response.first_name;
            self.surname = response.last_name;
        });
    }

    return self;
}
});

我的问题是,在收集过程中,这些值(名字和姓氏)仍然是空的(尽管模型中的 console.log 正确显示了它)。我该如何解决?

【问题讨论】:

    标签: backbone.js


    【解决方案1】:

    对FB.api 的Javascript 调用是异步的,所以FB.api 和return self 之间基本上没有延迟。由于您的console.log(model) 可能是在获取之后立即没有从FB.api 返回的数据,因为请求还没有结束。

    您可以做的是设置尝试在您的模型更新时放置一些回调并收听它,如果您更改模型触发update 方法类似...

    Friend.fetch( { success: function(model, response) { 
        if ( !model.get('first_name') ) {
            FB.api('/'+model.get('fbid'), function(fb_response) {
                model.set('first_name', fb_response.first_name);
                model.set('last_name', fb_response.last_name);
                console.log('model updated with facbook info', model);
            });
        }
    }});
    

    尝试在您的 FB.api 回调中运行(在您当前的代码中)console.log('updated'); 以查看我所说的延迟。

    【讨论】:

    • 谢谢,我按照你说的做了,触发了模型更新的事件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 2016-12-11
    • 2014-03-23
    • 1970-01-01
    相关资源
    最近更新 更多