问题描述
我使用的是与骨干RequireJS,我查看需要像,说20集之间进行切换,对应于各个RESTful API中。
I'm using Backbone with RequireJS, and my View needs to switch between like, say, 20 collections corresponding to respective RESTful APIs.
正常的方式处理家里的事,只是每种API的新集合需要加以界定,造成了巨大的臃肿codeBase的:
The "normal" way handles things fine, except that for each API a new Collection needs to be defined, resulting in a hugely bloated codebase:
专辑(×20倍)
define(function(require) {
var Backbone = require('backbone');
var c = Backbone.Collection.extend({
url: '/path/to/api-1'
});
return new c();
});
查看
define(function(require) {
var Backbone = require('backbone'),
c1 = require('./collections/collection-1'),
...
c20 = require('./collections/collection-20');
var v = Backbone.View.extend({
/* Some methods to toggle between Collections here */
});
return v;
});
这只是做收益℃;
集合内,并调用新C(网址:{url:/路径/要/ API-1}) ;
查看里面,我能够砍下高度重复的集合定义;但现在每个新C();
调用,这些API将始终捅检索数据的新副本,这是一种浪费资源和东西我不希望
By only doing return c;
inside the Collection, and calling new c({url: /path/to/api-1});
inside the View, I was able to cut down the highly duplicated Collection defines; but now on each new c();
calls, the APIs will always be poked to retrieve a new copy of data, which is a waste to resources and something I do not want.
有没有什么办法,使集合老大难?哪个更好满足以下所有条件:
Is there any way to make Collections "persistent"? Which better meets all of the criteria below:
- 对于每个API的相应的收集,只有一个
新
执行; - 每个集合可以共享/在不同的浏览访问使用RequireJS定义;
- 集合的定义可以通过所有API重用;
- 的全局命名空间是不是在所有的污染。
推荐答案
发现了一个相当hackish的解决方案:
Found a rather hackish solution:
包装你的收藏与其他的型号
define(function(require) {
var Backbone = require('backbone'),
m = require('../models/model');
var wrapper = Backbone.Model.extend({
initialize: function() {
var $_path = this.get('path');
var c = Backbone.Collection.extend({
model: m,
url: $_path,
initialize: function() {
this.deferred = this.fetch();
}
});
this.set({
collection: new c()
});
}
});
return wrapper;
});
然后,定义一个缓存容器:
Then, define a Cache container:
define(function(require) {
return cache = {};
});
需要缓存容器,并在您查看模块收集包裹两种:
Require both the Cache container and the wrapped Collection in your View module:
define(function(require) {
var $ = require('jquery'),
_ = require('underscore'),
Backbone = require('backbone'),
cache = require(cache),
wrapper = require('../collections/collection');
var v = Backbone.View.extend({
render: function($_path) {
var c = cache[$_path] || cache[$_path] = new wrapper({
path: $_path
}).get('collection'));
}
....
});
return v;
});
这样,你得到这两个实例化新的收藏与动态生成 $ _路径
值,并且能够从您的API缓存数据中取得这么长的页面的好处不刷新 - 实施的localStorage
如果您想将数据通过页面刷新坚持
This way you get both the benefits of instantiate new Collections with dynamically-generated $_path
values, and being able to cache data fetched from your APIs so long the page is not refreshed - implement localStorage
if you'd like the data to persist through page refreshes.
这篇关于骨干+ RequireJS:让收藏持久保留?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!