动态创建当前集合的实例

时间:2011-05-20 02:06:11

标签: javascript backbone.js

首先,为标题道歉 - 如果有人在阅读完问题后有更好的版本,请编辑或要求我。

我使用'where'方法扩展了核心Backbone Collection对象,该方法允许我对集合中的模型执行_.select。目前,这将返回包含模型的新vanilla Collection对象。我想要的是该方法返回与我调用的相同类型的Collection对象...

Backbone.Collection.prototype.where = function(a) {
  var execute = function(item) {
    ...
  };

  return new Backbone.Collection(this.select(execute));
};

var Accounts = Backbone.Collection.extend({...})

我想要的是,在return语句中将返回一个新的Account集合。但我不想在我扩展的每个集合中定义或扩展此方法。像下面的伪代码:

return new instanceof this(this.select(execute));

有意义吗?

1 个答案:

答案 0 :(得分:1)

我不是100%肯定你在问什么,但我认为你想在一个集合的实例上运行'where'并获得一个新的集合。刚刚在萤火虫中玩耍并想出了这个:

var Chapter  = Backbone.Model;
var chapters = new Backbone.Collection;

chapters.comparator = function(chapter) {
  return chapter.get("page");
};

chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));

Backbone.Collection.prototype.where = function(selector) {
 var newCol = new this.__proto__.constructor();
 var itemsToInsert = this.select(selector);
 itemsToInsert.forEach(function(item){ newCol.add(item) });
 return newCol;
};

chapters.where(function(c){ return c.get('page') == 1 });

`

这可能会做得更好..但这看起来很有用。