0
votes

Is there a way to prevent backbone from clearing out the changedAttributes object after changing a property (backbone version > 1). I simply try to increment a version attribute of a model when the model has changed after adding some data and then sync the model with all its changed attributes to the server;

var version = model.get('version');
model.set(data);
if(model.changedAttributes()) {
   model.set('version', version+1);
   model.save();
}

However since backbone cleared previous changes after the second set and in my backbone sync function i only post changedAttributes backbone will only posts the version attribute. So is there a way to changed and attribute and add it to the changed attribute object without clearing it. Otherwise i would be forced to make an extra server call for adding version

1

1 Answers

0
votes

You could make use of model.changed (http://backbonejs.org/#Model-changed)

var version = model.get('version');
model.set(data);
if (model.changedAttributes()) {

    // Remember the changes
    var changes = model.changed;

    // Set new version
    var newVersion = version + 1;
    model.set('version', newVersion);

    // Extend the changes with the new version
    model.changed = _.extend(changes, {
        version: newVersion
    });

    // Save to server
    model.save();

    // Reset changes to only contain the new version, so we don't break anything else
    model.changed = {
        version: newVersion
    };
}

I hope this helps.