我尝试为django + backbone.js创建rest-api,我遇到了麻烦,model.fetch()没有更新默认的模型值。哪里弄错了?
backbone.js模型
window.User = Backbone.Model.extend({
urlRoot: '/user/',
initialize: function() {
console.log("init Model User");
}
defaults: {
name: "Default title",
pass: 2011,
}
});
backbone.js view
window.UserView = Backbone.View.extend({
initialize:function () {
console.log('Initializing User View');
this.model.bind('change', this.render, this);
this.model.fetch ({
success: function () {
alert('success');
}
});
console.log(this.model);
this.render();
},
render:function () {
console.log('Print tpl UserView');
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
创建视图
var userView = new UserView({model: new User()});
django回复[{“name”:“LOLOLO”,“pass”:“12345”}]
的console.log(this.model)
打印
attributes: Object
0: Object
name: "LOLOLO"
pass: "12345"
__proto__: Object
name: "Default title"
pass: 2011
答案 0 :(得分:0)
您的console.log(this.model)
就在fetch
来电之后。
很有可能当您记录模型时,响应尚未从服务器到达,因此您只能获得默认值。
尝试将console.log调用放在fetch
的成功回调中