Backbone將很多下劃線方法擴展到Collection
類中,因此您可以擺脫某些東西。真的,你可能想要將這個集合本身作爲一種方法來實現,那麼我可能會用一個好的老式的for
循環來看看那些鍵,特別是如果我想擺脫它的話。
// in Backbone.Collection.extend
search: function(query, callback){
var pattern = new RegExp($.trim(query).replace(/ /gi, '|'), "i");
var collection = this;
collection.each(function(model) {
for(k in model.attributes){
if(model.attributes.hasOwnProperty(k) && pattern.test(model.attributes[k])){
callback.call(collection, model, k);
break; // ends the for loop.
}
}
});
}
// later
collection.search('foo', function(model, attr){
console.log('found foo in '+model.cid+' attribute '+attr);
});
也就是說,這隻會返回集合中的第一個匹配。您可能更喜歡將結果數組作爲[model,attribute]對返回的實現。
// in Backbone.Collection.extend
search: function(query, callback){
var matches = [];
var pattern = new RegExp($.trim(query).replace(/ /gi, '|'), "i");
this.each(function(model) {
for(k in model.attributes){
if(model.attributes.hasOwnProperty(k) && pattern.test(model.attributes[k])){
matches.push([model, k]);
}
}
});
callback.call(this, matches);
}
// later
collection.search('foo', function(matches){
_.each(matches, function(match){
console.log('found foo in '+match[0].cid+' attribute '+match[1]);
});
});
或者,如果你想要哪個型號相匹配的數組但不關心哪個屬性相匹配,您可以使用filter
// in Backbone.Collection.extend
search: function(query, callback){
var pattern = new RegExp($.trim(query).replace(/ /gi, '|'), "i");
callback.call(this, this.filter(function(model){
for(k in model.attributes){
if(model.attributes.hasOwnProperty(k) && pattern.test(k))
return true;
}
}));
}
// later
collection.search('foo', function(matches){
_.each(matches, function(match){
console.log('found foo in '+match[0].cid+' somewhere');
});
});
感謝您的回答。正常for..in將會很好。 –