简体   繁体   English

在Backbone.js中过滤模型(不是集合)

[英]Filtering Model (not collection) in Backbone.js

I was wondering if it was possible to filter a model like how a collection can be filtered? 我想知道是否可以过滤模型,如何过滤集合?

I'm doing a search functionality for a sport site and I want to be able filter the search results by type, ie football, tennis, basket-ball, swimming, athletic, etc... 我正在为一个运动网站进行搜索功能,我希望能够按类型过滤搜索结果,即足球,网球,篮球,游泳,运动等...

Here's my code (check the filterSearch() method): 这是我的代码(检查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: 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
            }


        ]
    }
]

Is there a specific reason you are using a Model for this case rather than a Backbone Collection? 您是否有特定原因使用模型而不是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});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM