0

我想知道是否可以像过滤集合一样过滤模型?

我正在为一个体育网站做一个搜索功能,我希望能够按类型过滤搜索结果,即足球、网球、篮球、游泳、运动等......

这是我的代码(检查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
            }


        ]
    }
]
4

1 回答 1

2

Is there a specific reason you are using a Model for this case rather than a Backbone Collection? You could easily have a Model for a single search result :

var searchResult = Backbone.Model.extend({});

and a collection to represent the search

var Search = Backbone.Collection.extend({
    model : searchResult,
    urlRoot: '/search',

    filterSearch: function(type) {
       return this.where({'type' : type});
    },
    parse: function(response) {
        return response.search;
    }

});

Otherwise just search over the array provided in the model:

...

filterSearch: function(type) {
    return _.where(this.get('search'), {'type' : type});
}
于 2013-10-14T17:06:10.520 回答