backbonejs在传递参数时过滤数据

时间:2014-01-25 07:10:30

标签: javascript backbone.js

我正在尝试这个 尝试过滤特定数据。

在菜单中,我有一个lista,当我点击其中时,我希望只获得有关它的信息。

 HourView= Backbone.View.extend({       


    initialize: function(){         
        this.template = _.template( $("#HourView").html() );
    },
    render: function () {
        var col = new HourCollection();     

        $.ajax({ //zeptojs
        async: true
        });
        col.fetch({ success: function() {

        }});

        //col.fetch({reset: true});
        $.ajax({ //zeptojs
        async: false
        });           
        col.where({"name": "Gamarra"});


        this.$el.html(this.template({ horarios: col.toJSON()   }));         
        return this;
    }
});

[   {     “名字”:“加马拉”,     “VES”:[       “00:00”     ]     “GRAU”:[       “01:00”     ]   },   {     “名字”:“格劳”,     “VES”:[       “08:00”     ]     “GRAU”:[       “07:00”     ]   }     ]

我正在尝试这个

   initialize: function(){  
        this.collection = new HourCollection();         
        this.collection.fetch({reset: true});
        this.collection.fetch({success: function(collection) {
            collection = collection.where({"name": "Gamarra"}); 
            console.log(JSON.stringify(collection))         
        }});            

        this.collection.on("sync", this.render, this);

        this.template = _.template( $("#HourView").html()     );            
    },
    render: function () {
        this.$el.html(this.template({ hs: this.collection.toJSON() }));         
        return this;
    }

1 个答案:

答案 0 :(得分:1)

方法where返回一个包含模型的数组(不是集合),因此您可以使用下划线在每个模型上调用toJSON方法,使其看起来像toJSON但已过滤

this.$el.html(this.template({ hs: _.invoke(this.collection.where({"name": "Gamarra"}), 'toJSON') })); 

第二种方法是在JSON上使用过滤器

this.$el.html(this.template({ hs: _.where(this.collection.toJSON(), {name: "Gamarra"}) })); 

第三种方法是在收集时使用chain方法(顺便说一下,它对你的数据不起作用:(我不知道它为什么会返回一个空数组)

this.collection.chain().where({ name: "Gamarra" }).value()