What is the right way to perform PATCH
request while saving model's attributes in Backbone.js?
相关问题
- Backbone.js PushState routes .htaccess only workin
- Updating a LayoutView's Model
- Disable Backbone.js hashes entirely, but keep push
- Is there an easy way to distribute a Flask server
- React + Backbone, Target container is not a DOM el
相关文章
- Get all models in backbone collection where attrib
- How can I dynamically set a className for a Backbo
- Nesting Views within Views in backbone js
- Backbone-relational hasmany best practices
- JavaScript error: “is not a constructor”
- Marionette + i18n in templates
- Rendering reCAPTCHA v2.0 widget within Backbone vi
- Backbone.js PUT/DELETE problems with Codeigniter R
You'll have to override
Backbone.sync
and extend the existing method mapperyou'll have to create your own patch method on a model like
I'm sure you can extend Backbone further to include
OPTIONS
andHEAD
if you needed toNote though, that even through jQuery supports the PATCH, OPTIONS and HEAD methods, your end-users' browser may not.
In addition to James Cropchos answer I want add the following, because this steals some hours from me and maybe helps someone else:
If you use
model.save(attributesToPatchObject,{patch: true})
like it is possible since backbone v.0.9.9 as stated in James Cropchos answer, you may wonder how to determine which attributes have changed since the last call ofmodel.save()
to pass them in asattributesToPatchObject
which is the first argument frommodel.save()
(ormodel.fetch()
if you didn't save the model lately).Backbone itself didn't keep track of those attributes. I thought the method
model.changedAttributes()
could fit, but as the backbone-doc says this method returnsSo this method didn't fit for this need. After some research I found out that backbone itself didn't keep track of unsaved attributes (I know, not a brilliant finding if I had read the docs more carefully).
I found out that backbone.trackit is a backbone plugin which exactly add the needed feature to backbone, by adding the method
unsavedAttributes()
to the model. The docs of backbone.trackit says about this method:It works like this:
Since the
unsavedAttributes()
returns false if there are no unsaved Attributes, you could additionally wrap yoursave()
statement within an if-condition which checks ifunsavedAttributes()
returns something other then false and only do your PATCH-Request if it's needed (because something changed).NOTE: You didn't have to call
fetch()
to usestartTracking()
so you can use this method even with newly created models (model.isNew()
returns true on that model), if there is a usecase for that.Hopes this may save someone a little bit of research time.
As of Backbone.js v0.9.9, you can simply pass
{ patch: true }
tosave()
.Read more: http://backbonejs.org/#changelog