marti_
marti_

Reputation: 124

backbonejs filter data when passing parameter

I am trying this try to filter a specific data.

In menu I have a lista I would like when I click in one i get only information about it.

 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;
    }
});

[ { "name": "Gamarra", "VES": [ "00:00" ], "GRAU": [ "01:00" ] }, { "name": "Grau", "VES": [ "08:00" ], "GRAU": [ "07:00" ] } ]

I am trying this

   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;
    }

Upvotes: 0

Views: 107

Answers (1)

Eugene Glova
Eugene Glova

Reputation: 1553

The method where returns an array (not collection) with the models, so you can use underscore to invoke toJSON method on each model so it will look like a toJSON but filtered.

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

The second way is just to use filter on JSON

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

Third way is to use chain method on collection (btw it doesn't work on your data :( and I don't know why it returns an empty array)

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

Upvotes: 1

Related Questions