Ale*_*lls 0 javascript backbone.js underscore.js
我只是想知道我们是否只能按属性过滤Backbone集合,而不能通过其他属性(如CID)过滤
它是否正确:
_.where(collection,{cid:'xyz'}) // filters by cid property?
_.where(collection,{attributes:{firstName:'foo'}}) // filters by attributes.firstName?
Run Code Online (Sandbox Code Playgroud)
我希望有人能理解我对如何使用嵌套属性过滤器的困惑.
有人可以解释一下,是否可以通过顶级属性(如CID)进行过滤,或者是否将Backbone集合配置为仅按属性进行过滤.
通常,您将使用_.where搜索对象数组来匹配属性.所以说_.where(collection, ...)没有多大意义,你想要搜索集合的models数组:
var a = _.where(collection.models, { cid: 'xyz' })
Run Code Online (Sandbox Code Playgroud)
这将或多或少与以下内容相同:
var a = [ ], i;
for(i = 0; i < collection.models.length; ++i)
if(collection.models[i].cid === 'xyz')
a.push(collection.models[i])
Run Code Online (Sandbox Code Playgroud)
_.where不知道用骨干收集的特殊结构,所以它不知道它应该看collection.models或有attributes机型里面,除非你告诉它.既然cid是财产的车型,而不是一个属性,上述_.where作品.
如果要搜索模型属性,那么您需要使用混合到集合中的Underscore方法,因为它们被调整为查看集合models或Collection#where了解attributes模型内对象的特殊内容.所以,如果你想寻找一个firstName属性,你会说:
collection.where({ firstName: 'foo' })
Run Code Online (Sandbox Code Playgroud)
不支持开箱即用地搜索嵌套对象.但是,所有的wheres只是包装器,_.filter所以你可以编写自己的谓词函数,做任何你想做的事情:
collection.filter(function(model) {
// Do whatever you want to model, return true if you like
// it and false otherwise.
});
Run Code Online (Sandbox Code Playgroud)
在大多数情况下,您应该尝试忽略Backbone.Collection#models和Backbone.Model#attributes属性,而是使用各种方法.通常有一种更好的方法来处理模型和属性,这些方法肯定会处理任何内部簿记.
| 归档时间: |
|
| 查看次数: |
183 次 |
| 最近记录: |