开发者

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.

Then I have the problem that when I call model.save() the model is saved to the wrong location. It is put to the url of the new id instead to th开发者_开发问答e url of the old id

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'

I want to save (put) {id: 'newId'} to the old 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. I did a similar thing when using backbone in Air app when saving straight to local database.

--edit

Or maybe Backbone.Model url.


This can also be achieved by setting the wait option to true on the save method of the model. This prevents the model's url from changing until after the server returns an updated representation with a new 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. 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.

Most (all...?) frameworks assume that an id is unique and unchanging.

Just know that changing the id has so many implications. Any references other objects have to that id will now be broken, urls referencing the previous id will be broken, etc...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜