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

Jos*_*sto 5 javascript backbone.js

学习骨干我创建一个像app的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);
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢!

abr*_*ham 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);
}
Run Code Online (Sandbox Code Playgroud)