Backbone and localStorage

To store Backbone models in localStorage, you can use the ID attribute as key and the serialized data as the value. However, remember that all the data in localStorage is mixed and this strategy will lead to identifier collisions.

Consider that you have two different models (contacts and invoices) with the same ID; when you store one of them in the localStorage, it will overwrite the other.

Another issue with localStorage is that when you want to retrieve data from the store before getting an item from the store, you need to know which key does it have. However, in localStorage, we don't have a clue about what IDs are currently in the store, therefore, we need a way to keep track of the IDs that are in the store at a given time.

To deal with these issues, you can create a well-known key in the store as an index of the IDs that are available for a given collection. See how it works in the following:

var data = localStorage.get('contacts'); // index name
varavailableIds = data.split(',');
varcontactList = [];

// Get all contacts
for (leti = 0; i<availableIds.length; i++) {
let id = availableIds[i];
let contact = JSON.parse(localStorage.getItem(id));
contactList.push(contact);
}

To prevent collision between collections of models with the same ID, you can generate prefixed keys for the collection items so that instead of having number keys such as 1, you can use keys such as contacts-1:

var data = localStorage.get('contacts'); // 1, 5, 6
varavailableIds = data.split(',');
varcontactList = [];

// Get all contacts
for (let i = 0; i<availableIds.length; i++) {
let id = 'contacts-' + availableIds[i];
let contact = JSON.parse(localStorage.getItem(id));
contactList.push(contact);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.142.85