为什么Backbone's collection create()方法未填充id

Why does Backbone's collection create() method not populate the id?

本文关键字:方法 id 填充 create collection Backbone 为什么      更新时间:2023-09-26

在下面视图的方法中,如果我正确理解create()方法,我的模型就会与服务器同步。但是,this.model.idconsole.log仍然返回undefinedthis.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,因为您的模型是新的,这意味着它还没有保存在服务器中。

因此,您可以使用.create函数中的success回调。我相信这样的东西会对你有用。

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响应,您将看到后端在创建模型时对您的响应。

如果需要,可以在调用create()时使用{ wait: true }选项;这样,模型只有在成功保存后才会添加到集合中。

将此与其他逻辑发生在集合的add事件上相结合可能会花费很长的时间。如果您需要能够区分新的create'd模型和以后添加到集合中的模型,则可以向create调用添加另一个选项(类似于newlySaved: true,然后在添加事件回调中检查options.newlySaved)。