【发布时间】:2013-03-21 01:04:27
【问题描述】:
我正在使用 Backbone.js 并尝试使用 fetch() 填充我的模型。我遇到的问题是返回的数据没有填充我的模型。我发现了一个类似的问题here。不同之处在于,在我的成功函数内部,我没有看到任何数据更改,也没有触发“更改”事件。
代码:
型号
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()在成功回调中说什么? -
company.get('name')似乎返回了名字!toJSON()返回[object Object]。这是有前途的!所有这一切的开始是在我的下划线模板中,我有<%= name =>和<%= address %>,它们曾经并且仍然是空的。有什么想法吗? -
你平时调用模板函数为
html = template(this.model.toJSON()),你是怎么做到的? -
这是问题的一部分。我将编辑原始帖子以包含我的观点。我在做
$(this.el).html(this.template());。当我在更新成功回调以包含数据参数后将其更改为$(this.el).html(this.template(this.model.toJSON()));时,我得到了它的工作。
标签: javascript jquery backbone.js