I\'ve been studying Backbone.js for a few weeks, and I feel comfortable using views with models, routers, and collections.
I still have some big gaps:
The id
property on a model is automatically assigned based on the id
set in the model’s attributes hash. Ideally, this is the ID that you receive from the rest API for the resource that you are querying. On the other hand, cid
is an ID temporarily assigned to each model and is useful until an actual ID is determined for the object. For example, a model pushed to a collection that has not yet been persisted can be addressed using cid
, until it is saved in the database and an actual ID is generated for it.
What is the connection between
id
,cid
, andidAttribute
? How do they affect each other?
Both the cid and id should be unique id's for the model, and can be used to retrieve a model from a collection.
The difference between the two is that the cid
is assigned by backbone.js client side and is useful if you don't have an actual id, either because the model hasn't been saved yet to the server or perhaps you aren't even saving it to a db (maybe you're using localStorage). The id
attribute should be the id of the model that comes from your server (that is what the id is in your db). idAttribute
tells backbone which "field" coming from your server it should use to update the id
attribute, by default this is set to "id" but as it says in the documentation if your server uses something else you can set it to that (the example given is setting it to "_id".
When exactly does a new model get its ID? Is the server responsible for assigning it? Do I need to add it to the
defaults
of the model (maybe as a function)? Maybe theaddNewModel
function should do that?
They should get the new id's when saved to the server and you shouldn't need to set it manually (based on the idattribute
) unless you need more control over the process.
id
is server model id, cid
is client id.
id - id that might be manually set when the model is created, or is populated when model has been saved on the server (see "idAttribute" at the bottom to see the connection). This is the id that is sent to the server when model is loaded or updated from server e.g., for a model Person this call will be made if id is 123, "/person/123"
cid - unique id set my backbone model for internal use
idAttribute - this decides which property will act as the unique id (default is "id") when the model has been saved on the server e.g., a model's unique key on the server might be defined by "personId", so when fetch is called model will map the server response from "personId" to id in the backbone model.