概述
我有一个 JSON 对象被传递到我的主干模型。我在主干模型中有一个解析函数来转换一些传入的属性。问题是当我获取这个模型时,属性没有被解析,只是添加到模型中。底部的图像显示,它没有将密码转换为密码并删除密码,而是将密码添加到对象的属性中。
这是我的代码:
JSON
当我使用 postman 调用我的网络服务时,我得到响应:
{"type":null,"idTeacher":1,"name":"Sean","password":"tst","email":null,"dob":1392940800000}
型号:
window.Teacher = Backbone.Model.extend({
urlRoot: "http://localhost:8080/SIMS/resource/teacher",
defaults: {
"id": null,
"Name": "",
"Password": "",
"email": "",
"dob": "",
"type": ""
},
parse: function(response){
response.id = response.idTeacher;
response.Password = response.password;
response.Name = response.name;
delete response.name;
delete resoponse.password;
delete response.idTeacher;
return response;
}
});
window.TeacherCollection = Backbone.Collection.extend({
model: Teacher,
url: "http://localhost:8080/SIMS/resource/teacher",
parse: function(response){
return response;
}
});
Main.js//这是
before: function(callback) {
if (this.teacherList) {
if (callback) callback();
} else {
console.log('........................................javascript........');
this.teacherList = new TeacherCollection();
console.log('Loading List: Size: ' + this.teacherList.length);
this.teacherList.fetch({success: function() {
console.log('........... ftech success...........');
$('#contents').html( new TeacherListView({model: app.teacherList}).render().el );
if (callback) callback();
}});
}
}
如果我调试 Backbone,我可以看到我的解析没有解析任何变量,并且解析中的删除调用也不起作用。
更新答案
感谢您的帮助。我在集合类中没有代码这一事实是一个问题。但第二个原因是我没有循环访问集合来更改每个属性。
最佳答案
这是因为当您为集合调用 fetch 方法时,调用的解析方法是集合的解析,而不是教师模型的解析。 当您从集合中调用 fetch 方法时,集合期望收到一组模型,而不仅仅是您所描述的一位老师
关于javascript - Backbone 无法正确解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22053538/