我正在使用Backbone.js并试图使用fetch()来填充我的模型。我遇到的问题是返回的数据没有填充我的模型。我发现了一个类似的问题here。不同之处在于,在我的成功函数中,我没有看到任何数据变化,也没有发生“更改”事件。骨干js不使用fetch填充数据模型()
的代码:
模型
window.Company = Backbone.Model.extend({
urlRoot: "/api/company",
defaults:{
"id":null,
"name":"",
"address":"",
"city":"",
"state":"",
"phone":""
},
events: {
'change': 'doChange'
},
doChange: function(event) {
alert('company changed');
}
})
路由器
var AppRouter = Backbone.Router.extend({
routes:{
"":"home",
"company/:id":"companyDetails"
},
initialize:function() {
var user = new User();
this.headerView = new HeaderView({
model: user
});
$('.header').html(this.headerView.el);
console.log("router initialized.");
},
companyDetails: function (id) {
var company = new Company({
id: id
});
company.fetch({
success: function(){
console.log('company.id is ' + company.id);
console.log('company.name is ' + company.name);
console.log('company.address is ' + company.address);
$("#content").html(new CompanyView({
model: company
}).el);
}
});
}
});
JSON
{"address":"555 Main St","name":"Confused Technologies","id":"8dc206cc-1524-4623-a6cd-97c185a76392","state":"CO","city":"Denver","zip":"80206","phone":"5551212"}
名称和地址始终未定义。我必须俯视一些简单的事情?
编辑
包括错误地离开了模型传递到模板中的视图。
查看
window.CompanyView = Backbone.View.extend({
initialize:function() {
this.render();
console.log('CompanyView initialized');
},
render:function (eventName) {
$(this.el).html(this.template());
return this;
}
})
在成功回调中,'company.get('name')'或'company.toJSON()'说什么? – 2013-03-21 01:42:33
'company.get('name')'似乎返回名称! 'toJSON()'返回'[object Object]'。这是有希望的!开始所有这一切都是在我的下划线模板中,我有'<%= name =>'和'<%= address%>',它们仍然是空的。有什么想法吗? – laduke 2013-03-21 02:50:44
您通常将模板函数调用为'html = template(this.model.toJSON())',那么您怎么做? – 2013-03-21 03:32:06