Backbone.js retrieves the actual attribute settings

I have a basic base model, its urlRoot attribute urlRoot set, and the corresponding server-side target returns the correct JSON output (both the JSON string and the application/json header).

I call the selection as follows:

 var athlete = new Athlete({ id: 1 }); athlete.fetch(); 

at this point if i add

 console.log(athlete); 

I can see the model and test it in firebug. I can open the attribute object and see all the values ​​returned from the server.

BUT if I do a:

 console.log(athlete.get('name')); 

I get undefined (the name appears under the attributes in the DOM check mentioned above)

also performs:

 console.log(athlete.attributes); 

returns an object containing only {id: 1} , which is the argument that I passed when creating the model.

If I create a model as follows:

 var athlete = new Athlete(<JSON string copypasted from the server response>); 

then everything works fine, the .get() method returns everything I ask, and athlete.attributes shows all the values.

What am I doing wrong?

+8
javascript
source share
2 answers

fetch is asynchronous, which means that the data will not be available if you immediately call console.log(athlete.get('name')) after retrieving.

Use events to notify when data is available, such as

 var athlete = new Athlete({id: 1}); athlete.on("change", function (model) { console.log(model.get('name')); }); athlete.fetch(); 

or add a callback to your selection

 var athlete = new Athlete({ id: 1 }); athlete.fetch({ success: function (model) { console.log(model.get('name')); } }); 

or use the promise returned by fetch :

 athlete.fetch().then(function () { console.log(athlete.get('name')); }); 
+18
source share

As a quick note when using events in this example. In my case, this is not with change , because this event fires with every change. So sync does the trick.

 var athlete = new Athlete({id: 1}); athlete.on("sync", function (model) { console.log(model.get('name')); }); athlete.fetch(); 
+1
source share

All Articles