简体   繁体   English

Backbone.js:将更改的 model id 保存到服务器的最佳方法

[英]Backbone.js: Best way to save a changed model id to the server

I want to allow the user to change the id of a model in a collection.我想允许用户更改集合中 model 的id

Then I have the problem that when I call model.save() the model is saved to the wrong location.然后我遇到的问题是,当我调用model.save()时,model 被保存到错误的位置。 It is put to the url of the new id instead to the url of the old id它被put新id的url而不是旧id的url

var model = collection.get('oldid');
model.set({id: 'newId'}); // set by the user through the ui
model.save();

This will save to collectionUrl/ + 'newId' instead of collectionUrl/ + 'oldId'这将保存到collectionUrl/ + 'newId'而不是collectionUrl/ + 'oldId'

I want to save (put) {id: 'newId'} to the old url.我想将 {id: 'newId'} 保存(放置)到旧的 url。

What is the most consistent way of doing this?这样做的最一致的方法是什么?

This is so edge case that there's no best practices for it.这是非常极端的情况,没有最佳实践。

I would try overwriting Backbone.sync and/or Backbone.Model save to make backbone behave that way.我会尝试覆盖Backbone.sync和/或Backbone.Model save以使主干以这种方式运行。 I did a similar thing when using backbone in Air app when saving straight to local database.在直接保存到本地数据库时,我在 Air 应用程序中使用主干时做了类似的事情。

--edit - 编辑

Or maybe Backbone.Model url .或者也许是Backbone.Model url

This can also be achieved by setting the wait option to true on the save method of the model.这也可以通过在 model 的保存方法上将 wait 选项设置为 true 来实现。 This prevents the model's url from changing until after the server returns an updated representation with a new id.这可以防止模型的 url 在服务器返回具有新 ID 的更新表示之后发生变化。 I've tried it out and it seems to work great!我已经尝试过了,它似乎工作得很好!

I don't think any framework, server side or client side would support that out of the box.我认为任何框架、服务器端或客户端都不会开箱即用地支持它。 Best way would be to do your own AJAX request to your own endpoint on the server.最好的方法是向服务器上您自己的端点发出您自己的 AJAX 请求。 I would question why you need to do that though, I can't think of any reason that would be a good idea.我会质疑你为什么需要这样做,但我想不出任何理由是个好主意。

it's a bit roundabout, but you could create a separate unique id (specified using the model's idAttribute), then 'id' is just another property.这有点迂回,但您可以创建一个单独的唯一 id(使用模型的 idAttribute 指定),然后“id”只是另一个属性。

Most (all...?) frameworks assume that an id is unique and unchanging.大多数(所有...?)框架都假设 id 是唯一且不变的。

Just know that changing the id has so many implications.只知道更改 id 有很多含义。 Any references other objects have to that id will now be broken, urls referencing the previous id will be broken, etc...其他对象对该 id 的任何引用现在都将被破坏,引用先前 id 的 url 将被破坏,等等......

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

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