Cal*_*ass 2 backbone.js underscore.js
我有一个集合self.models
.我还有一个对象数组,其中包含我希望应用于我的集合的字段和过滤器filterArr
.一个例子是:
[{field: "Account", filter: "123"}, {field: "Owner", filter: "Bob"}]
Run Code Online (Sandbox Code Playgroud)
问题是,我不确定我是如何迭代我的每个模型只返回那些filterArr
适用的模型,我知道它必须是这样的,但这是硬编码的:
self.models = _.filter(self.models, function (model) {
model = model.toJSON();
return model.Account === "123" && model.Owner === "Bob";
});
Run Code Online (Sandbox Code Playgroud)
首先,下划线的过滤器返回一个Array
,所以你在这里有效地做的是用过滤后的数组替换你的集合.这样的事情会更合适:
this.filtered = _.filter(this.models, ...);
Run Code Online (Sandbox Code Playgroud)
Backbone Collection实现了大多数下划线的有用功能.所以上面的解决方案远非最优化(事实上它并不是按照你想要的方式工作),而是做这样的事情:
this.filtered = this.models.filter(function() {...});
Run Code Online (Sandbox Code Playgroud)
最好的方式获得,并通过名称设置模型字段是目前get
和set
功能骨干的Model
,那么为什么不使用他们?Model.toJSON()
有效,但你只是attributes
不必要地复制-hash.
this.filterObj = { // Why not make it an object instead of array of objects
"Account": "123",
"Owner": "Bob"
};
this.filtered = this.models.filter(function(model) {
// use the for in construct to loop the object
for (filter in filterObj) {
// if the model doesn't pass a filter check, then return false
if (model.get(filter) !== filterObj[filter]) return false;
}
// the model passed all checks, return true
return true;
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
归档时间: |
|
查看次数: |
3563 次 |
最近记录: |