javascript – 在嵌套对象中搜索文本(Backbone.js集合作为示例)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 在嵌套对象中搜索文本(Backbone.js集合作为示例),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2537字,纯文字阅读大概需要4分钟。
内容图文
![javascript – 在嵌套对象中搜索文本(Backbone.js集合作为示例)](/upload/InfoBanner/zyjiaocheng/815/d530e591710b494aaf6873724a45bbab.jpg)
我有一个backbone.js集合,我需要在上面进行全文搜索.我手头的工具如下:
Backbone.js,underscore.js,jQuery
对于那些不熟悉骨干的人:
骨干集合只是一个对象.在集合内部有一个带模型的数组.每个模型都有一个包含属性的数组.我必须在每个属性中搜索字符串.
我正在使用的代码是:
query = 'some user input';
query = $.trim(query);
query = query.replace(/ /gi, '|');
var pattern = new RegExp(query, "i");
// this.collection.forEach is the same as _.each
// only it get's the models from the collection
this.collection.forEach(function(model) {
var check = true;
_.each(model.attributes, function(attr){
if(pattern.test(attr) && check){
// Do something with the matched item
check = false;
}
}, this);
}, this);
也许我使用的工具之一有更好的方法来处理这个?
解决方法:
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]);
});
});
或者,如果您想要匹配但不关心匹配哪个属性的模型数组,则可以使用过滤器
// 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');
});
});
内容总结
以上是互联网集市为您收集整理的javascript – 在嵌套对象中搜索文本(Backbone.js集合作为示例)全部内容,希望文章能够帮你解决javascript – 在嵌套对象中搜索文本(Backbone.js集合作为示例)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。