0

I have a simple backbone app that fetches a collection from a JSON file which works fine. But I really want to fetch a single modal from the collection. Ideally I want to fetch the model using the locale attribute.

How can I do this?

So far I have the following code,

var Item = Backbone.Model.extend({
   defaults:{
       "locale":"",
       "name":"",
   }
});

var ItemsCollection = Backbone.Collection.extend({
   model: Item,
   url: 'data/items.json'
});

var items = new ItemsCollection(); 
var itemView = new ItemView({model: items});
items.fetch({
   success: function() {
      itemView.render();
   }
})

Json structure is this,

[
    {
        "locale": "gb",
        "name": "British"
    },
    {
        "locale": "de",
        "name": "German"
    }
]

Thanks

halfer
  • 19,824
  • 17
  • 99
  • 186
jeg
  • 9
  • 2
  • 1
    Have you read the [Backbone Collection documentation](http://backbonejs.org/#Collection)? – mu is too short Jun 11 '17 at 02:11
  • I have indeed and im still not understanding what I need to do. – jeg Jun 11 '17 at 18:35
  • 2
    Have you looked at the `findWhere` and `where` methods? – mu is too short Jun 11 '17 at 19:23
  • 1
    Possible duplicate of [Backbone - How to find a model from a collection according to some other attribute but not ID?](https://stackoverflow.com/questions/14420599/backbone-how-to-find-a-model-from-a-collection-according-to-some-other-attribu) – Emile Bergeron Jun 12 '17 at 13:52
  • Im currently fetching the entire collection and passing that to the view and using findwhere inside the view to get the model I want but that that feels wrong. It feels like I should be able to fetch only the model I want and then pass only that single model to the view for render. – jeg Jun 13 '17 at 18:21
  • 1
    Well it may feel wrong but that's the Backbone way. It's designed to assume more of a in-memory representation of server data in the client. So get all the data, make collections in client, edit, send back changes etc. That said, you _do_ have a way to just get from server what you want. Since the `collection.fetch()` is a wrapper for jquery `$.ajax` just add a `.data` option with your parameter just as you'd do in jQuery. – vassiliskrikonis Jun 15 '17 at 07:10

0 Answers0