Search code examples
backbone.jsbackbone-local-storage

Generate nicer id from localstorage/collections


So I've dived into Backbone.js framework and I've finally came to the point where I play with models/collections.

Here's the thing. I'm using localstorage as database and my problem is I'm not statisfied to see my ids look like this:

id : "53ec77a0-8b06-c31b-d72c-a350741898d0"

Is there a simple solution to set the id's to a more proper look, like 1, 2, 3 or even like the cid. I've tryed it out with cid but it isn't good either because it changes everytime you fetch the data from localstorage...

Thanks in advance!

/Haris


Solution

  • Hmmm, I am not sure why you'd want to do that, it's really the adapter's job to define the IDs, and ensure their uniqueness, not yours!

    If you look at the code of backbone's localstorage, you can see the line that is creating your issues here:

     create: function(model) {
        if (!model.id) {
          model.id = guid();
          model.set(model.idAttribute, model.id);
        }
        ...
      }
    

    So, two ways to go about that:

    1. Fork backbone localstorage to replace the call to guid() (which just generate random ids, it doesn't try to ensure uniqueness) by something nicer.

    2. Give your own ID before calling save(). For the localstorage, it's kind of acceptable since there are no real constraints on the ids, but then it becomes your job to make it unique, especially across multiple running of your app [closing+reopening the browser] (you can keep the lastId in your local storage and increment it every time, to make it behave like a Primary Key with AutoIncrement in a DB, I guess)