简体   繁体   English

bone.js更新其属性已更改的模型

[英]backbone.js updating a model whose attributes have been changed

In SQL you would use the UPDATE command to update a row, how do you update a model in SQL where it's attributes have been changed from say another JSON Object. 在SQL中,您将使用UPDATE命令来更新行,如何在SQL中更新其属性已从另一个JSON对象更改的模型。

I would like to do this in such a way so that it only changes the attributes that have been changed and not the whole model, I have seen the model.changedAttributes() command, but not sure how to use this. 我希望以这种方式进行操作,以便它仅更改已更改的属性,而不更改整个模型,我已经看到了model.changedAttributes()命令,但不确定如何使用它。

Thanks 谢谢

Edit: 编辑:

I have tried this: 我已经试过了:

//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..
  }                     
}); 

It returns with an error, "undefined is not a function" 它返回错误,“未定义不是函数”

As I understand you would like to save data from the model to the server with RESTful service and don't want to send all the data of the model but only those attributes which have been changed only. 据我了解,您希望使用RESTful服务将数据从模型保存到服务器,并且不希望仅发送那些已更改的属性来发送模型的所有数据。 For this purpose you should use patch method: 为此,您应该使用patch方法:

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

You may send only attrs in this case or 在这种情况下,您只能发送attrs

model.save({patch: true})

just attributes which have been changed (in this case attrs will be model.changedAttributes() ) 只是已更改的属性(在这种情况下, attrs将为model.changedAttributes()

From backbone documentation: 从主干文档:

If instead, you'd only like the changed attributes to be sent to the server, call model.save(attrs, {patch: true}) . 如果相反,您只希望将已更改的属性发送到服务器,请调用model.save(attrs, {patch: true}) You'll get an HTTP PATCH request to the server with just the passed-in attributes. 您将仅使用传入的属性将HTTP PATCH请求发送到服务器。

I am working on this right now myself. 我现在正在自己进行这项工作。

Your logic looks correct from the documentation. 根据文档,您的逻辑看起来正确。 After your getModel.set('interest', 'rolling stones'); getModel.set('interest', 'rolling stones'); I would do 我会做

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.

If are not using the Backbone.sync methods then in order for backbone to work well I'd recommend overriding these methods in your classes. 如果未使用Backbone.sync方法,则为了使骨干网正常工作,我建议您在类中重写这些方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM