Search code examples
javascriptbackbone.jslocal-storagebackbone-local-storage

How to use different localStorages with Backbone.localStorage?


I have two different Model collections in backbone. However on both collections i'm just using numbers as their id, e.g (1,2,3,4...) If i store them in the same storage, I'd have errors and conflicts with the IDs. Is it possible to assign one localStorage for one collection and the other for the other collection? Thank you.

products.forEach(function (product) {
            localStorage.setItem(product.get("id"), JSON.stringify(product));
        });

for one collection like this. I don't instantiate the store or anything, just use setItem method on the localStorage variable, and if i'd do this for the second item guess, it would fail.


Solution

  • Localstorage only allows to store key / value pairs. You'd need to assemble the key yourself to make sure it's unique. You can concatenate the entity-type in front of the key (example: "PRODUCT").

    products.forEach(function (product) {
       localStorage.setItem("PRODUCT" + product.get("id"), JSON.stringify(product));
    });
    

    And then use the same logic on getItem()