Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...