Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a Backbone.js Collection live only in memory (not persisted)?

Using Backbone.js, I use Collections to fetch and synchronize data between the client and a Ruby server. That works pretty fine.

Now I would like to use it also to store data in memory (in present case, it would be a collection of articles in a cart).

Is there a way to do this without persisting data on the server nor in the local storage, ie. have the Collection living only in memory?

Whenever I try to set the collection's url property to a null value, I am getting an Uncaught TypeError: Cannot call method 'create' of null. So... I guess this is not the right way to go!

If this not possible, what is the best design to have server and localStorage dealing with different classes in the same application?

like image 966
yoann-h Avatar asked Jan 27 '26 19:01

yoann-h


1 Answers

In the beginning is easy, just don't use fetch() to populate the Collection and use reset() instead. Check reset() documentation.

But maybe you start having issues with Collection.create(), Model.destroy() and so on. So you have to be careful using this methods.. maybe you can use Collection.add() instead of Collection.create(), but I don't see good replacement for Model.destroy().

I think the most elegant way to solve your problem should be to rewrite the sync() method for your memory Collection and Model.

This is a very guess, written in the fine air:

// code simplified and no tested
var MemoryCollection = Backbone.Collection.extend({
  sync: function( method, model, options ){
    options.success.apply();
  }
})

but maybe it can help you to start working in this direction.

If this is working you still have to use Collection.reset() instead of Collection.fetch().

like image 95
fguillen Avatar answered Jan 30 '26 07:01

fguillen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!