Created
August 20, 2016 20:07
-
-
Save Aleksey-Danchin/9588bf360a116859e128b8ebd458655b to your computer and use it in GitHub Desktop.
Watch service
This file contains hidden or 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 Watch (obj, scheme, handler, pathOriginal = [], _obj = {}) { | |
scheme.forEach(fieldName => { | |
const path = pathOriginal.map(e => e); | |
if (typeof fieldName === 'string') { | |
path.push(fieldName); | |
if (['string', 'number', 'boolean'].indexOf(typeof obj[fieldName]) !== -1 || obj[fieldName] === null) { | |
_obj[fieldName] = obj[fieldName]; | |
delete obj[fieldName]; | |
Object.defineProperty(obj, fieldName, { | |
enumerable: true | |
, get: () => _obj[fieldName] | |
, set: newValue => { | |
const oldValue = _obj[fieldName]; | |
_obj[fieldName] = newValue; | |
handler(path, newValue, oldValue); | |
} | |
}); | |
} else if (obj[fieldName] instanceof Array) { | |
_obj[fieldName] = obj[fieldName]; | |
delete obj[fieldName]; | |
obj[fieldName] = new Proxy(_obj[fieldName], { | |
set: function (target, property, value) { | |
if (property === 'length') return true; | |
target.push(value); | |
handler(path, newValue, oldValue); | |
return true; | |
} | |
}); | |
} | |
} else if ((typeof fieldName === 'object') && !(fieldName instanceof Array)) { | |
Object.keys(fieldName).forEach(_fieldName => { | |
path.push(_fieldName); | |
Watch(obj[_fieldName], fieldName[_fieldName], handler, path, _obj[_fieldName] = {}) | |
}); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment