我正在寻找一种管理集合集合的方法。请参阅下面的示例代码:
function Collection() {
this.items = []; //Contains items, which have a date associated with them
}
Collection.prototype.doSomethingOnItems = function(){};
function SuperCollection() {
this.collections = []; //An array of Collection objects
this.group = []; //A vector with a string that designates the group (e.g. 2013, 2012)
}
SuperCollection.prototype.groupCollections = function(items, groupType) {
//Group by year, month, day, etc...
//For example, given a timeframe of 2012-2013, items in 2012 are put in collections[1], those from 2013 are in collections[2]
}
有没有更好的方法来管理这样的结构?
答案 0 :(得分:0)
我喜欢把事情做成通用/抽象的
function Collection(items)
{
// Could/should do some checking/coercion here
this.items = items || [];
};
Collection.prototype.add = Collection.prototype.push = function(item)
{
this.items.push(item);
};
Collection.prototype.remove = function() {} ....
// etc...
// A single Group
function Group(name, items)
{
this.name = name;
this.items = new Collection(items);
};
// A Collection of groups
function Groups()
{
this.groups = new Collections();
};
或者您可以使用Collection的原型(一种继承形式)扩展Groups的原型 例如(使用jQuery或任何其他库,或编写自己的库)
function Groups()
{
};
$.extend(Groups.prototype, Collection.prototype);
让我们留下:
var groups = new Groups();
groups.add(new Group("2013", []));
所有这些允许您将逻辑分开,并在Group / Group'类'中包含与Collection'class'分开的辅助方法