Backbone.js正在更新属性被更改的模型

backbone.js updating a model whose attributes have been changed

本文关键字:模型 属性 js 更新 Backbone      更新时间:2023-09-26

在SQL中,您将使用UPDATE命令来更新行,如何在SQL中更新模型,其中它的属性已经从另一个JSON对象更改。

我想这样做,这样它只改变已经改变的属性,而不是整个模型,我已经看到了model. changedattributes()命令,但不确定如何使用它。

感谢编辑:

我已经试过了:

//code to update model
usersCollection.fetch({
  success: function() {
    var getModel = usersCollection.where(checkIDJSON);
    //update that partcular attribute
    getModel.set('interest', 'rolling stones');
    console.log("Users:" + usersCollection.toJSON());
  }, error: function() {
    // something is wrong..
  }                     
}); 

返回错误"undefined is not a function"

据我所知,您希望使用RESTful服务将模型中的数据保存到服务器,并且不希望发送模型的所有数据,而只想发送那些已更改的属性。为此,您应该使用patch方法:

model.save(attrs, {patch: true})

在这种情况下您可以只发送attrs

model.save({patch: true})

只是已经更改的属性(在本例中attrs将是model.changedAttributes())

来自主干文档:

如果您只希望将更改后的属性发送到服务器,则调用model.save(attrs, {patch: true})。您将获得一个向服务器发送的HTTP PATCH请求,其中包含传入的属性。

我正在做这件事。

您的逻辑从文档中看起来是正确的。在你的getModel.set('interest', 'rolling stones');之后,我会做

getModel.save(); //saves the model to the database (or whatever you have setup)
userCollection.reset(); // reloads the collection from the database (or whatever you have setup.

如果没有使用主干。我建议在你的类中重写这些方法