Question

I am building an app which will load a JSON file and use that to populate all models. I have to keep a list of changes and then post this back to the server after a 'publish' button is clicked.

I think a combination of using Backbone.LocalStorage and using model change events to then track which models have changes sounds right but it'd help to hear from someone who's gone down this route or solved similar!

Does this approach makes sense? Is there a better one?

Was it helpful?

Solution

If you are trying to track individual changes and not just the final state before saving, then it is probably a good idea to create an Audit model or something similar. You can hook into the change events as you suggested. Saving those Audit models to the server can be done using the standard version (or some batched modification) of Backbone.sync whenever you want. That model might look something like this:

var Audit = Backbone.Model.extend({
  defaults : {
    auditableType: "", auditableId: null, auditedChanges : ""
  },
  paramRoot : "audit"
});
var Audits = Backbone.Collection.extend({
  model : Audit
});

Then create a Model prototype that all audited models can extend from:

var audits = new Audits();
var AuditedModel = Backbone.Model.extend({
  initialize : function (options) {
    this.listenTo(this, "change", function (model, options) {
      audits.add({
        auditableType : this.paramRoot,
        auditableId : this.id,
        auditedChanges : this.changed
      });
    });
  }
});

Now just extend from your AuditedModel for any models you want to track changes on.

var User = AuditedModel.extend({
  paramRoot : "user",
  // Do whatever
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top