I’m making a Backbone app now and using a backbone.localstorage plugin to persist the data. My app has some sortable items so I hope every time I sort the items, the data order in localStorage will also change. And next time I refresh the whole page, the page will be rendered by the sorted data. But it seems that backbone.localstorage will persist the data in its creation order. Could someone give me some ideas on this?
I’m making a Backbone app now and using a backbone.localstorage plugin to persist the
Share
If you want your models to appear in an explicit order then include a
comparatorin your collection and, possibly, a position number in each model.Local storage is:
Note the key/value pairs, that means that you’re dealing with, more or less, a big hash table and those are usually unordered. Furthermore, from the fine specification:
So there is no particular order inside local storage. If you want a specific order, you have to arrange for it yourself.
In your case, you’d probably have a
positionorindexproperty in your models that would behave like an array index; then, in your collection:You could also use a two argument
comparatorfunction:You’d have to maintain the position indexes as you move models around but that shouldn’t be terribly difficult. You could also order the data by
positionafter pulling it out of local storage but before putting it in your collection and then assignpositionvalues while writing the models into local storage.