Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js partial model update

Is it possible to send just the modified properties of a model when saving the changes?

BTW, Are there any "official" Backbone.js group/mailing list to ask this kind of questions?

like image 311
ggarber Avatar asked Mar 11 '11 13:03

ggarber


People also ask

Is Backbone JS still used?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

Is Backbone JS frontend or backend?

Backend Synchronization BackboneJS is use with the front-end and back-end systems, allows the synchronization with the backend to provide support to RESTful APIs.

Is backbone a MVC?

Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).


2 Answers

Backbone does not support this out of the box, but you have all the tools to make that happen. If you look at Backbone.sync you will see that it calls toJSON on your model to get the actual data to send. Now you might have to tweak this out, but here is the gist of it:

initialize: function(){   this.dirtyAttributes = {} }, set: function(attrs, options){   Backbone.Model.prototype.set.call(this, attrs, options);   _.extend(this.dirtyAttributes, attrs); }, toJSON : function(){   json = this.dirtyAttributes;   this.dirtyAttributes = {};   return json; } 

If you want a complete solution you need to apply the same logic to unset, clear, save, etc. But I guess you get how to do this. I put the reset of the dirty attributes in the toJSON function, but it should really be in the success callback (when calling save).

like image 129
Julien Avatar answered Oct 04 '22 10:10

Julien


Currently backbone does not support sending part of the model to the server. It would be an interesting addition though.

If you browse the source you can see that Backbone.sync (the part of backbone that is responsible for communicating with the data store) is one of the simplest components in backbone and simply wraps the ajax support in jQuery or Zepto.


UPDATE

starting backbone version 0.9.10, partial model update is supported natively via

model.save(attrs, {patch: true}) 
like image 40
Andrew Hare Avatar answered Oct 04 '22 09:10

Andrew Hare