Backbone.js how to work with fetched Items
I'm trying to learn Backbone.js and I seem to be having an issue with fetch on a model. I have:
window.News = Backbone.Model.extend({
urlRoot: "/rest/news"
});
window.NewsItems = Bac开发者_如何学编程kbone.Collection.extend({
model: News,
url: "/rest/news"
});
window.NewsView = Backbone.View.extend({
el: $(".newsItem"),
events: {
"click .edit": "editNews"
},
editTemplate: $('#tmpl-edit-news-item').template(),
editNews: function(evt) {
console.log("EDIT CLICKED");
var ele = $(evt.target);
var news = new News({id:1});
news.fetch();
console.log(news);
console.log(news.get('title');
}
});
new NewsView();
I have an elements on page that have a class="edit" data-id="$ID". When I click the element everything goes as expected. Backbone runs the editNews function, "EDIT CLICKED" shows up in the console and console.log(news) outputs an object. Inside that object I noticed there is an attributes field that contains the json of the news item loaded by the server. So the server is working and sending back json. There is a title field that is set to "Test News Title", but running console.log(news.get('title')) returns undefined.
Do I need to pass the fetched data to something to turn it into a backbone model? I thought using fetch took the json data thats returned and put it into the model.
Additional Info:
url requested: http://localhost/rest/news/1
response data: {"class":"org.backbonetest.News","id":1,"content":"This is test content","dateCreated":"2011-09-20T16:19:56Z","lastUpdated":"2011-09-20T16:19:56Z","shortDescription":"","title":"Test News Title"}
It should be like this:
editNews: function(evt) {
console.log("EDIT CLICKED");
var ele = $(evt.target);
var news = new News({id:1});
// fetch is asynchronous process so we will bind handler to model's change event
news.bind('change', function(model, value) {
console.log(news);
console.log(news.get('title');
}, this)
news.fetch();
}
Okay so since the fetch is asynchronous, I can't call console.log on it right away. Adding a success function allows the object to work as a model.
var news = new News({id:1});
news.fetch();
console.log(news);
console.log(news.get('title');
Becomes
news.fetch({success: function() {
console.log(news.get("title"));
},
processData: true
});
This returns the proper title.
精彩评论