Skip to content

Instantly share code, notes, and snippets.

@tabiodun
Created July 19, 2020 19:10
Show Gist options
  • Save tabiodun/d5794c4c52133da88c566f29093a6e86 to your computer and use it in GitHub Desktop.
Save tabiodun/d5794c4c52133da88c566f29093a6e86 to your computer and use it in GitHub Desktop.
function applyChanges() {
this.isSaving = true;
for (const key of Object.keys(this.buffer)) {
this[key] = this.buffer[key];
}
this.buffer = {};
delete this.isSaving;
}
function rollback() {
this.buffer = {};
}
export const createProxy = (object) => {
object.buffer = {};
object.applyChanges = applyChanges.bind(object);
object.rollback = rollback.bind(object);
return new Proxy(object, {
get(target, prop) {
if (prop === 'isDirty') {
return Boolean(Object.keys(target.buffer).length);
}
if (target.buffer[prop]) {
return target.buffer[prop];
}
return target[prop];
},
set(obj, prop, value) {
if (prop === 'isSaving') {
obj[prop] = value;
}
if (prop === 'buffer') {
obj[prop] = value;
}
if (!obj.isSaving) {
obj.buffer[prop] = value;
} else {
obj[prop] = value;
}
return true;
},
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment