Backbone collection.create()不返回更新的模型

时间:2012-04-06 18:15:35

标签: javascript backbone.js

学习骨干我创建一个类似Twitter的应用程序。所以你知道Twitter每N秒向服务器发送一个GET请求来检查新的推文。如果有新的推文,它会创建隐藏的 li 元素,并显示带有“N个新推文”的按钮。如果单击它,它会显示隐藏的 li 元素,显示新推文。 但是当您添加新推文时,行为会有所不同:推文是可见的。您无需单击按钮即可查看。

我已经为隐藏的推文做了第一部分。对于发布新推文并显示直接的部分,我认为通过创建新模型,调用collection.create()并触发正确的事件会很容易,例如:

var newTweet = new Tweet();
newTweet.set( /* set the attributes here. Some attributes are missing, because they are calculated server side */ );

var created_tweet = this.collection.create( newTweet, { silent: true, wait: true } ); // I choose silent=true because the add event on my collection is in charge of adding the new hidden tweets when there are new ones on the server
this.collection.trigger("posted_new_tweet", created_tweet);

然后,我的收藏集订阅了“posting_new_tweet”事件,因此每次用户发布新推文时,都会调用我的收藏集的特定方法。 这种方法工作正常,直到我因触发器中传递的变量created_comment而出现错误:它不是“完整”。我的意思是该模型有一些属性,如“id”或*“created_on”*未定义。这些属性是在服务器端计算的,但我认为如果我通过 wait = true ,它会等待并使用服务器给出的响应更新我的模型(当 POST 时请求发送到服务器,它返回json中新创建的模型

我的模型不应该具有服务器端属性吗?对于这样的事情,这是正确的方法吗?如果不是,我怎么能有2种不同的方法来显示集合视图?

谢谢!

1 个答案:

答案 0 :(得分:14)

即使您传递create

{ wait: true }仍然是异步的。差异是没有wait模型将立即添加到集合中,而wait骨干网不会将其添加到集合中,直到服务器成功响应。

您应该做的是向create添加成功回调,以便在服务器响应时触发事件。

var created_tweet = this.collection.create( newTweet, { silent: true, wait: true, success: this.successCallback } );

// Add successCallback as a method to the collection
successCallback: function(collection, response) {
  // I'm not 100% positive which values are passed to this function. Collection may actually be the new model.
  this.collection.trigger("posted_new_tweet", created_tweet);
}