我正在寻找一种方法来管理集合的集合。参见下面的示例代码:
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]
}
有更好的方法来管理这样的结构吗?
我喜欢让事情尽可能的一般化/抽象化
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();
};
或者你可以用集合的原型扩展组的原型(继承的一种形式)例如(使用jQuery,或任何其他库,或编写自己的)
function Groups()
{
};
$.extend(Groups.prototype, Collection.prototype);
剩下的是:
var groups = new Groups();
groups.add(new Group("2013", []));
所有这些都允许您保持逻辑分离,以及在组/组'类'中包含辅助方法,这些'类'与您的集合'类'分开