Basically I want to fetch a JSON file and store it in a model. However, when I try to access the attributes via get()
it returns undefined. So lets say the JSON file has an array games that consists of objects with some attributes. It doesn't really matter. Just want to save them in the model and access them. So I'm doing something like this.
var player = Backbone.Model.extend({
initialize: function(app, options) {
this.app = app;
var _this = this;
this.fetch({
url: "someurl",
success: function() {
console.log("success");
}
});
}
});
var instplayer = new player();
instplayer.on('change', function(){
console.log(model);
console.log(model.get(games));
})
So I figured that I need an event to ensure that get()
is called when the data is really available. But this still returns undefined. What do I need to do?
I don't know if it's a typo or not but you are not passing
model
to thecallback
it should be
then
games
must be astring
not avariable
.Another thing I suggest you to be aware of is what the
json
returns; sometimes you have to override theparse
function to get the exact results.Again if your fetching an
array
and not a single object, maybe you should use acollection
ofplayers
So I imagined you have a json for your player like this (I've mocked it here for the example below to work):
And here's a complete working example of how I would deal with managing and rendering this kind of data: