Created
July 19, 2020 19:10
-
-
Save tabiodun/d5794c4c52133da88c566f29093a6e86 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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