我正在尝试学习Backbone.js,我似乎遇到了模型上的fetch问题 . 我有:
window.News = Backbone.Model.extend({
urlRoot: "/rest/news"
});
window.NewsItems = Backbone.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();
我在页面上有一个元素,它们有一个class =“edit”data-id =“$ ID” . 当我点击元素时,一切都按预期进行 . Backbone运行editNews功能,“EDIT CLICKED”显示在控制台中,console.log(新闻)输出一个对象 . 在该对象内部,我注意到有一个属性字段,其中包含服务器加载的新闻项的json . 所以服务器正在工作并发送回json . 有一个 Headers 字段设置为“测试新闻 Headers ”,但运行console.log(news.get('title'))返回undefined .
我是否需要将获取的数据传递给某些内容才能将其转换为主干模型?我认为使用fetch获取返回的json数据并将其放入模型中 .
附加信息:
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"}
2 回答
它应该是这样的:
好的,因为fetch是异步的,我不能马上调用它上面的console.log . 添加成功函数允许对象作为模型工作 .
变
这将返回正确的 Headers .