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

2019-06-23 11:11发布

要了解骨干进出口创建一个Twitter类似的应用程序。 所以,你知道Twitter发送GET请求到服务器的每N秒,以检查是否有新的鸣叫。 如果有新的鸣叫,它创建隐藏的li元素,并显示有“N新推文”的按钮。 如果你点击它,它显示隐藏的li元素,呈现出新的鸣叫。 但是,行为是不同的,当你添加一个新的tweet:鸣叫是可见的。 你不必点击按钮才能看到。

我已经取得了第一部分,用于隐藏鸣叫。 对于发布新的鸣叫,并将其显示照片直接的部分,我认为这将是很容易通过创建一个新的模式,调用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);

然后,我的收藏订阅到事件“posted_new_tweet”,所以用户发布新的鸣叫,我收藏的具体方法被调用每次。 这种方法工作正常,直到我由于触发传递的变量created_comment错误:它不是“完全”。 我的意思是,该模型具有一定的属性“身份证”或*“created_on” *这是不确定的。 这些属性计算服务器端,但我认为,如果我通过等待= true时 ,它会等待并更新我的服务器(当POST请求向服务器发出给出的响应模型,它返回新创建的模型JSON)

如果不是我的模型有服务器端藏汉属性? 难道这样的事情是正确的做法? 如果它不是,我怎么能有2种不同的方法来显示一个集合视图?

谢谢!

Answer 1:

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);
}


文章来源: Backbone collection.create() does not return the updated model