Backbone.sync clarification

2019-08-01 15:24发布

问题:

After reading the docs, this is my understanding of sync.

I instantiate some Backbone.Model and call Collection.create(). create() eventually calls sync() and the Model is POSTed to the server. Then there is a sync in the opposite direction such that the Model on the client is given an id.

Does this update then trigger componentDidUpdate()?
Note: componentDidUpdate is a ReactJS thing, so if that doesn't make sense, the question reduces to "Is the client-side model updated and the view re-rendered?"

Since inside of my componentDidUpdate() I am making a call to save() to keep everything up to date, this subsequently makes a call to sync() which then fires a PUT request (because the Model already has an id).

I'm asking, because in my current application, creating a TodoItem seems to result in a POST and then a PUT which I find redundant. Perhaps it is for an unrelated reason.

It actually fires two POSTS and then two PUTS when adding one item, but that is another question.

回答1:

The first time you save a model (one which doesn't have an id) it will make a POST, thereafter it will make a PUT (update). I think you are confusing when to use create/add/save:

  • Use save at any point to save the current client collection/model state to the server
  • Use add to add Model(s) to a collection (a single Model, an array of Models, or an array of objects which contain attributes and let the collection create them)
  • Use create as a shorthand for creating a model, adding it to the collection, and syncing the collection to the server.

My guess is that you are calling create and save in one operation - you should be using add and save instead, or just create.

The view will not automatically update for you, you will need to listen to changes or events on the collection/model and update the view yourself - there is no equivalent of componentDidUpdate. For example:

initialize: function() {
    this.listenTo(this.collection, 'sync', this.onCollectionSync);
},

onCollectionSync: function() {
    this.render();
}