Store Backbone models in localStorage
It's time to use what you have learned about localStorage
to store and retrieve objects. The DataStore
object is responsible to transform models into strings to be stored in localStorage:
class DataStore { constructor(name) { this.name = name; // Keep track of all ids stored for a particular collection this.index = this.getIndex(); } getIndex() { var index = localStorage.getItem(this.name); return (index &&index.split(',')) || []; } }
The DataStore object needs a name to be used as a collection index prefix. The first use case is to create a new item:
class DataStore { // ... create(model) { // Assign an id to new models if (!model.id&& model.id !== 0) { model.id = generateId(); model.set(model.idAttribute, model.id); } // Save model in the store with an unique name, // e.g. collectionName-modelId localStorage.setItem( this.itemName(model.id), this.serialize(model) ); // Keep track...