calypso icon indicating copy to clipboard operation
calypso copied to clipboard

Implement change tracking for models.

Open kevinswiber opened this issue 10 years ago • 0 comments

Harmony proxies would be awesome here, but we can't use them yet.

Because the model-based approach requires mapping of properties to the backing data store, we can use that information to create our own proxy.

In the example below, createProxy would have to be implemented into the model instantiation logic.

Change tracking will be important when Calypso implements save functionality. For document-level databases, this won't apply so much, but for relational, row-based databases that allow field-level updates, this will be perfect.

var ConstructorMap = require('calypso/constructor_map');

var Book = function() {
  this.title = null;
  this.author = null;
};

var mapping = function(config) {
}

var map = new ConstructorMap();
map.of(Book)
  .map('title')
  .map('author');

var createProxy = function(model) {
  var config = model.__orm_model_config__;
  var fields = Object.keys(config.fieldMap);
  fields.forEach(function(field) {
    model.prototype['_' + field] = null;
    model.prototype.__orm_change_tracking__ = [];
    Object.defineProperty(model.prototype, field, {
      get: function() {
        return this['_' + field];
      },
      set: function(val) {
        this['_' + field] = val;
        var changeTracking = this.__orm_change_tracking__;
        if (changeTracking.indexOf(field) === -1) {
          changeTracking.push(field);
        }
      }
    });
  });
};

createProxy(Book);

var book = new Book();

book.title = 'Hello';
book.author = 'World';

console.log(book.__orm_change_tracking__);

book.__orm_change_tracking__ = [];

book.title = 'Yo';

console.log(book.__orm_change_tracking__);

// Output:
// [ 'title', 'author' ]
// [ 'title' ]

kevinswiber avatar Oct 11 '13 22:10 kevinswiber