在下面的视图方法中,如果我create()
正确理解该方法,则模型将与服务器同步。但是,console.log
ofthis.model.id
仍会返回,undefined
并且会this.model.isNew()
返回true
。POST在返回的JSON对象中显示一个ID,而模型对象的属性也显示一个ID,那么为什么它们不能正确反映在模型中?创建新视图时,需要设置ID。
submitForm: function( e ) {
e.preventDefault();
this.model.set( this.$( '.editForm' ).serializeObject() );
if ( this.model.isNew() ) {
collection.create( this.model );
console.log( this.model, this.model.id, this.model.isNew() );
new MyView({
model: this.model
}).render().appendNode();
} else {
this.model.save();
}
this.closeForm();
}
因此,Jacob,这里的问题只是在呈现视图之前,您需要等待服务器的响应。您的情况this.model.id
将是undefined
因为您的模型是新的,这意味着它尚未保存在服务器中。
因此,您可以做的是使用success
该.create
函数的回调。我相信这样的事情会为您工作。
if (this.model.isNew()) {
collection.create({
// or you can use this.model (if it is an object)
attribute_x: 'val',
attribute_y: 'val'
}, success: function(response){
// here your model with have an id
console.log(response);
new MyView({
model: response.model // check your response
}).render().appendNode();
});
} else {
new MyView({
model: this.model
}).render().appendNode();
}
因此,如您所见,在success
回调中,我们渲染View
。如果您console.log
做出响应,您将看到后端在创建模型时对您的响应。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句