简体   繁体   中英

Backbone.js Singleton Collection

I'm building an application with Backbone.js and require.js. My collections get the data from the backend via the fetch() function. Now I have a case where the fetch function is expensive and the data for this specific collection won't change and I'll have such more collections. So I want to keep the data/collection in the memory. But I'm struggling by the implementation. I want to keep the lazy loading given by require.js. What are usual and "clean" ways to handle that?

Use javascript closures, something like:

var getCollection = (function(){
  var coll;

  return function(){
    if( ! coll){
      coll = new MyCollection();
      coll.fetch();
    }
    return coll;
  }
}());

The first time you call getCollection , the collection will be fetched. Then, each subsequent call will get the cached value.

For more on these kinds of patterns, take a look at "Javascript patterns" by Stoyan Stafanov ( http://shop.oreilly.com/product/9780596806767.do )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM