Search code examples
javascriptbackbone.jsbackbone.js-collections

Is it possible to generate a unique id for new models in Backbone collection?


I have a Backbone collection from serer with attributes id and name.

I get new name from input.

var a = $('#newFoodtype').val();

And create new model and adding to collection;

var b = new app.Foodtype({ "name" :a });
this.collection.add(b);

The new model doesn't have an id attribute. I know all model have a id.

How to generate a unique id and set this to new models.

I will delete some models in collection, therefore collection.length is good idea. I will send this to the server. One solution is to send only the "name" and generate the "id" on the server during the insert to the DB.

Is it possible to generate this from the client side?


Solution

  • One solution is to send only the "name" and generate the "id" on the server during the insert to the DB.

    The id, if saved in a database, should be handled by the database. Never try to increment the last id or use the collection length as a unique identifier.

    Temporary client id: cid

    Backbone gives model and views a cid property which is a "client id". It is unique only to that client instance and won't be unique after a refresh. It serves to identify models before they are saved and given their final id.

    var newModel = Backbone.Model({ name: "new model" });
    console.log(newModel.cid); // e.g.: "c123"
    

    Generating GUID

    If it's not an id for the database, but only a unique identifier for business logic, you could generate a GUID with a low chance of collision.

    See Create GUID / UUID in JavaScript?