我想知道是否可以过滤模型,例如如何过滤集合?
我正在为一个运动网站进行搜索功能,我希望能够按类型过滤搜索结果,即足球,网球,篮球,游泳,运动等......
这是我的代码(检查filterSearch()
方法):
define([
'jquery',
'backbone',
'underscore',
'models/model'],
function($, Backbone, _, Model){
var Search = Model.extend({
urlRoot: '/search',
defaults: {
query: ''
},
initialize: function(attrs, options) {
if (typeof options === 'object') {
this.router = options.router;
}
},
filterSearch: function(type) {
this.filter(function(data) {
return data.get(type);
});
}
});
return Search;
});
JSON:
[
{
"search": [
{
"result": {
"query": "Vettel is world champion"
},
"type": "Formula 1",
"id": 1
},
{
"result": {
"query": "Romario of Brazil world cup 1994"
},
"type": "football",
"id": 2
},
{
"result": {
"query": "federe won again"
},
"type": "tennis",
"id": 3
}
]
}
]
答案 0 :(得分:2)
您是否有特定原因使用模型而不是Backbone Collection?您可以轻松拥有单个搜索结果的模型:
var searchResult = Backbone.Model.extend({});
以及代表搜索的集合
var Search = Backbone.Collection.extend({
model : searchResult,
urlRoot: '/search',
filterSearch: function(type) {
return this.where({'type' : type});
},
parse: function(response) {
return response.search;
}
});
否则只需搜索模型中提供的数组:
...
filterSearch: function(type) {
return _.where(this.get('search'), {'type' : type});
}