我们正在使用Ember。数据版本11。我们的关系是这样的:
Social.Account = DS.Model.extend({
name: DS.attr("string"),
username: DS.attr("string"),
messages: DS.hasMany("Social.Message"),
});
Social.Message = DS.Model.extend({
text: DS.attr("string"),
created: DS.attr("date"),
account: DS.belongsTo("Social.Account"),
posts: DS.hasMany("Social.Post")
});
Social.Post = DS.Model.extend({
text: DS.attr("string"),
created: DS.attr("date"),
message: DS.belongsTo("Social.Message"),
});
用户创建一条Message,然后可以将其发送到多个社交媒体帐户,每个帐户都会生成一个Post。在提交时,创建了Message和Post记录,但是我们在Post记录中获取了从Twitter返回的信息。我们当前使用的代码如下所示:
saveMessage: function(text){
var acct = Social.Account.find(this.get("id")),
msg = Social.store.createRecord(
Social.Message,
{
text: text,
account: acct,
created: new Date()
}
);
acct.get("messages").addObject(msg);
Social.store.commit();
msg.addObserver('id', this, function(){
var timeoutID = window.setTimeout(function(){
msg.reload();
console.log('reloading');
}, 5000);
});
}
只要我点击提交消息和Post都加载在UI中。问题是Post缺少native_url属性,该属性只能在向Twitter发出http请求后获得。奇怪的是,如果我用一个警告窗口替换addObserver调用的内容,native_url值就会弹出。我不知道为什么,但它确实是。
无论如何,所以我的问题是我要做什么来获得Post对象更新的数据从服务器,并更新UI与新数据。
在没有看到您的所有代码之前,我不能保证这就是解决方案。但是你应该做的一件事是不要依赖setTimeout
来进行Ember回调。请使用Ember.run.later.
Ember.run.later(this, function() {
this.reload();
console.log('reloading');
}, 5000);
任何在Ember之外异步发生的事情都应该被封装在RunLoop中。因此,如果你的回调是插件的一部分或其他类似的东西,你也可以把它全部包装在Ember.run.