1

我正在寻找一种管理集合集合的方法。请参见下面的示例代码:

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]
}

有没有更好的方法来管理这样的结构?

4

1 回答 1

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();
};

或者您可以使用集合的原型(一种继承形式)扩展组的原型,例如(使用 jQuery 或任何其他库,或编写您自己的)

function Groups()
{

};

$.extend(Groups.prototype, Collection.prototype);

这给我们留下了:

var groups = new Groups();

groups.add(new Group("2013", []));

所有这些都允许您将逻辑分开,并在与您的 Collection 'class' 分开的 Groups/Group 'classes' 上包含辅助方法

于 2013-06-17T01:25:45.197 回答