I have problems when i try to fetch data to my Backbone model from the server. You get a response in JSON from from the server which I think looks to be right formatted. Can you see anything wrong with it? It looks like:
[{"id":"1","name":"Fawad Hassan","email":"fawad@test.com"},{"id":"2","name":"Bill
Gates","email":"bill@test.com"},{"id":"3","name":"Steve
Jobs","email":"steve@test.com"},{"id":"4","name":"Naveed
Ahmad","email":"naveed@test.com"},{"id":"5","name":"Mr Zee","email":"zee@test.com"}]
My code for the Backbone project looks like this, and I can’t really find the problem there either.
window.AppModel = Backbone.Model.extend({
url: function() {
return 'http://dev.local/ci/index.php/site/userpost';
}
});
window.AppContr = Backbone.Collection.extend({
model: AppModel,
initialize: function() {
this.model = new AppModel;
}
});
window.App = new AppContr({name: "Markus"});
window.AppView = Backbone.View.extend({
el: $("#content"),
initialize: function() {
this.render();
},
render: function() {
console.log(App.model.toJSON());
}
});
App.model.fetch();
window.View = new AppView;
You are doing a
fetchon a Model, but returning Collection in response. That is main problem.Second problem is that you are calling
renderon AppView totally random, i.e. it does not have anything to do withmodelorcollection. Maybe there would be nothing inmodelwhen you render view. You should bind rendering tocollectionormodelwithbind. Than whenever you callfetchyour view will re-render, which is one of main benefits of Backbone 🙂Here comes the code 🙂