I have read other posts here and it looks like most of the time this boils down to fetch being async. I don't think that is my problem because 1. I test the results in the success callback of fetch and 2. I can console.log(model.toJSON())
in the js console later and it still is not updated
Notes: I am getting a good JSON response from the API and I can get the data by putting 'parse' in my model declaration like so
parse: function(data){
alert(data.screenname);
}
Here is my code, why is the model not being updated with the fetch call
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="vendor/components/underscore/underscore-min.js"></script>
<script src="vendor/components/backbone/backbone-min.js"></script>
</head>
<body>
Hello
<script>
$.ajaxSetup({
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Basic " + window.btoa("username" + ":" + "password"));
}
});
var User=Backbone.Model.extend({
parse: function(data){
alert(data.screenname);
},
urlRoot: 'http://api.myapi.com/user'
});
var user=new User({id:'1'});
user.fetch({
success: function(collection, response, options){
console.log(response);
console.log(user.toJSON());
}
});
</script>
</body>
</html>
When I log response, it show a good json coming back, but user.toJSON just shows the id as 1.
I can use parse
in the model declaration to manually assign each value in the model from the response, but that seems like a dumb way to do it. I was under the impression that fetch()
was supposed to populate the model with the result from the server.
UPDATED Here is the response I get back from the server
{"id":1,"email":"test@email.com","password":"pass","screenname":"myname","id_zipcode":1,"id_city":1,"date_created":"2014-12-25 12:12:12"}
Here are the response headers from my API:
HTTP/1.1 200 OK
Date: Tue, 04 Feb 2014 18:31:41 GMT
Server: Apache/2.2.24 (Unix) DAV/2 PHP/5.5.6 mod_ssl/2.2.24 OpenSSL/0.9.8y
X-Powered-By: PHP/5.5.6
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Authorization, Origin, X-Requested-With, Content-Type, Accept
Set-Cookie: PHPSESSID=pj1hm0c2ubgaerht3i5losga4; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 139
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
You have overridden your parse()
method to effectively do nothing. It should return all the attributes to set on your model; you have not returned anything, hence, nothing was being set on the model.
It should look like this.
var User=Backbone.Model.extend({
parse: function(data){
alert(data.screenname);
return data; //all attributes in data will be set on the model
},
urlRoot: 'http://api.myapi.com/user'
});