Backbone.js - id vs idAttribute vs cid

25,471

Solution 1

What is the connection between id, cid, and idAttribute? 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 the addNewModel 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.

Solution 2

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.

Solution 3

id is server model id, cid is client id.

  • server model: such as Rails Model
  • client model: backbone model
Share:
25,471

Related videos on Youtube

Daniel
Author by

Daniel

Updated on October 27, 2020

Comments

  • Daniel
    Daniel over 3 years

    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:

    1. What is the connection between id, cid, and idAttribute? How do they affect each other?

    2. 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 the addNewModel function should do that?