[英]IgnoreCase backbone.js collection?
我一直在嘗試使用collection.where在骨架.js集合上執行不區分大小寫的搜索,我只是意識到,集合中搜索值和模型字段值的大小寫必須匹配。 我找到了這個示例,但是在哪里可以覆蓋行為或有替代方法? 謝謝
collection.findWhere({ 'Fname': val })
和
collection.where({ 'Fname': val })
//僅在字符串大小寫匹配時起作用。
var myCollection = Backbone.Collection.extend({
// define your own case insensitive where implemented using .filter
iwhere : function( key, val ){
return this.filter( function( item ){
return item.get( key ).toLowerCase() === val.toLowerCase();
});
}
});
我選擇覆蓋集合中的where和findWhere,以允許caseInsensitive選項:
//case-insensitive where
where: function(attrs, first, options){
options = options || {};
if (_.isEmpty(attrs)) return first ? void 0 : [];
return this[first ? 'find' : 'filter'](function(model) {
for (var key in attrs) {
if (options.caseInsensitive) {
if (attrs[key].toLowerCase() !== model.get(key).toLowerCase()) return false;
} else {
if (attrs[key] !== model.get(key)) return false;
}
}
return true;
});
},
findWhere: function(attrs, options) {
return this.where(attrs, true, options);
}
並通過以下方式調用:
collection.findWhere({username: "AwEsOmE"}, {caseInsensitive: true});
它不是很漂亮,但原始實現也不是。 O_O
將其作為拉取請求打開也很好,但是可以將where函數中的“ first”變量重構為選項的關鍵。 這是我要做的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.