简体   繁体   English

Backbone.js Singleton集合

[英]Backbone.js Singleton Collection

I'm building an application with Backbone.js and require.js. 我正在使用Backbone.js和require.js构建应用程序。 My collections get the data from the backend via the fetch() function. 我的集合通过fetch()函数从后端获取数据。 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. 我想保持require.js给出的延迟加载。 What are usual and "clean" ways to handle that? 有什么通常的和“干净的”方式来解决这个问题?

Use javascript closures, something like: 使用javascript闭包,例如:

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. 首次调用getCollection ,将获取该集合。 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 ) 有关这些模式的更多信息,请查看Stoyan Stafanov的“ Javascript模式”( http://shop.oreilly.com/product/9780596806767.do

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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