Backbone collection.create () does not return an updated model

Find out that I am creating Twitter as an application. So you know that Twitter sends a GET request to the server every N seconds to check for new tweets. If there are new tweets, he creates hidden li elements and shows a button with "N new Tweets". If you click on it, it will display the hidden li elements, showing new tweets. But the behavior is different when you add a new tweet: tweets are visible. You do not need to click a button to see it.

I have already done the first part, for hidden tweets. Regarding the publication of the new tweet and shown on it, I thought it would be easy to do this by creating a new model, calling collection.create () and firing the correct event, for example:

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

Then my collection is subscribed to the event "published_new_tweet", so every time a user publishes a new tweet, a specific method of my collection is called. This approach worked fine until I got an error due to the created_comment variable passed in the trigger: it is not "complete". I mean, the model has attributes like "id" or * "created_on" *, which are undefined. These attributes are computed on the server side, but I thought that if I pass wait = true , it will wait and update my model with the response given by the server (when a POST request is made to the server, it returns the newly created model in json)

? ? , ?

!

+5
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);
}
+14

All Articles