gpt4 book ai didi

javascript - 动态创建当前集合的实例

转载 作者:行者123 更新时间:2023-11-30 06:04:23 24 4
gpt4 key购买 nike

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

我已经使用“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({...})

我想要的是,在返回语句中返回一个新的 Account 集合。但是我不想在我扩展的每个集合中都定义或扩展这个方法。类似于以下伪代码:

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

有道理吗?

最佳答案

我不是 100% 确定你在问什么,但我认为你想在集合实例上运行“where”并取回一个新集合。只是在 Firebug 中玩耍并想出了这个:

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

`

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

关于javascript - 动态创建当前集合的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6066773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com