我在不同的文章中看到了关于如何从 RequireJS 定义返回主干集合(或 View ,就此而言)的不同示例。例如:
define(['models/person'], function( person ) {
var personCollection = Backbone.Collection.extend({
model: person,
url: "api/person"
});
// do this?
return new personCollection();
// or this?
//return personCollection;
});
这两种方法都有内存优势吗?是否有标准的设计模式来规定应该使用哪个?
同样的问题也适用于 View ,因为我也看到它们以两种方式完成。
最佳答案
我会采用第二种方式,因为那样您会收到对“蓝图”的引用,而不是对象本身。在大多数情况下,人们应该希望自己初始化对象创建。
此外,即使您只想创建集合的单个实例,我也建议您使用这样的工厂方法:
define(['models/person'], function( person ) {
var personCollection = Backbone.Collection.extend({...}),
singleCollection,
export = {
getInstance = function (options) {
if (!singleCollection) {
singleCollection = new personCollection(options);
}
return singleCollection;
}
}
return export;
});
然后你可以这样调用它:
require('models/person', function (person) {
var personCollection = person.getInstance(options);
}
关于javascript - 在 requirejs 中返回 Backbone 集合的标准方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15637601/