Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetching data from server with backbone and creating model and collection

I have a url http://anexampleproject/api/players which returns list of players in json format.

How can i create model and collection of it and alert name in console.

example of url returned json:

 [
       {
          "id": 1,
          "name": "Lily",
          "age": 14,
          "city": New York,
       },
       {
         "id": 2,
         "name": "BIlly",
          "age": 14,
          "city": New York,
      }
    ]
like image 284
Lasang Avatar asked Feb 17 '23 04:02

Lasang


1 Answers

var data = [{
    "id": 1,
    "name": "Lily",
    "age": 14,
    "city": "New York"
}, {
    "id": 2,
    "name": "BIlly",
    "age": 14,
    "city": "New York"
}];

var MyModel = Backbone.Model.extend({
    defaults: {
        "id": "",
        "name": "",
        "age": 0,
        "city": ""
    }
});

var MyCollection = Backbone.Collection.extend({
    model: MyModel
});

var myCollection = new MyCollection(data);

EDIT:

Using url

var MyCollection = Backbone.Collection.extend({
    url: "http://anexampleproject/api/players",
    model: MyModel
});

var myCollection = new MyCollection();
myCollection.fetch({
    success: function(){

    },
    error: function(){

    }
});
like image 176
Diode Avatar answered May 06 '23 03:05

Diode