Backbone: No data added to model on fetch()
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":"fa开发者_高级运维wad@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 fetch
on a Model, but returning Collection in response. That is main problem.
Second problem is that you are calling render
on AppView totally random, i.e. it does not have anything to do with model
or collection
. Maybe there would be nothing in model
when you render view. You should bind rendering to collection
or model
with bind
. Than whenever you call fetch
your view will re-render, which is one of main benefits of Backbone :)
Here comes the code :)
window.Person = Backbone.Model.extend({});
window.Addressbook = Backbone.Collection.extend({
url: 'http://dev.local/ci/index.php/site/userpost',// declare url in collection
model: Person
}
window.Addresses = new AddressBook();
window.AppView = Backbone.View.extend({
el: $('#content'),
initialize: function() {
Addresses.bind('reset', this.render); // bind rendering to Addresses.fetch()
},
render: function(){
console.log(Addresses.toJSON());
}
});
window.appview = new AppView();
Addresses.fetch();
精彩评论