我试图了解Backbone Collection findWhere()
函数的工作原理,并且在代码中看到了这一点:
// Return models with matching attributes. Useful for simple cases of
// `filter`.
where: function(attrs, first) {
var matches = _.matches(attrs);
return this[first ? 'find' : 'filter'](function(model) {
return matches(model.attributes);
});
},
// Return the first model with matching attributes. Useful for simple cases
// of `find`.
findWhere: function(attrs) {
return this.where(attrs, true);
},
我试图了解这部分的作用:
return this[first ? 'find' : 'filter'](function(model) {
return matches(model.attributes);
});
this['find'](function(model){ ... })
这部分实际上是做什么的? 最佳答案
您可以在javascript中使用方括号符号代替点符号,并且在您遇到这种情况时,方括号符号非常方便。因此,以下内容相同:
foo.['bar']
foo.bar()
在这一行:
return this[first ? 'find' : 'filter'](function(model) {
如果第一个值返回true,将使用
this.find()
,否则将使用this.filter()
。