Skip to content

Instantly share code, notes, and snippets.

@robneville73
Last active December 29, 2017 02:33
Show Gist options
  • Save robneville73/97559a8b16c9f803751840a0d1c08e7b to your computer and use it in GitHub Desktop.
Save robneville73/97559a8b16c9f803751840a0d1c08e7b to your computer and use it in GitHub Desktop.
ECMAScript 5 way of redefining a property on an object at runtime with an explicit get/set pair that would allow one to emit an event (e.g. think redux action) upon certain property changes
var rob = {
orderid: 'ORDER123',
customerid: '7',
customer: {
firstname: 'Rob',
lastname: 'Neville'
},
observed: false,
orderlines: [
{
lineid: 1,
productid: 'MODERNSCROLL',
product: {
vendorid: 'ROB'
},
qty: 1
},
{
lineid: 2,
productid: 'RECLINER',
product: {
vendorid: 'IAN'
},
qty: 3
}
]
};
function observeProperty(obj, key, parent_path, callbackFn) {
console.log(key, obj);
const hidden_key = `_${key}`;
obj[hidden_key] = obj[key];
delete obj[key];
console.log(`defining ${obj}[${key}]`);
Object.defineProperty(obj, key, {
get: function() { return this[hidden_key]; },
set: function(value) {
if (this[hidden_key] !== value) {
callbackFn(parent_path);
}
this[hidden_key] = value;
}
});
}
function observeProperties(obj, paths, event) {
let observerHandler = function(path) {
console.log(event, path);
}
obj._observerHandler = observerHandler;
paths.forEach(path => {
let object_path = path.split('.');
let observing_object = obj;
object_path.slice(0, -1).forEach(key => {
observing_object = observing_object[key];
});
let observed_key = object_path[object_path.length - 1]
observeProperty(observing_object,
observed_key,
path,
obj._observerHandler);
});
}
@robneville73
Copy link
Author

of course, this assumes there's no naming collisions with _+original property name, etc.

@robneville73
Copy link
Author

probably need to check that obj[key] is a scalar, object or array and then for arrays, need a way of tracking changes to any element in the list.

@robneville73
Copy link
Author

might want to look at proxies too since that might be a good way to intercept array changes (changes in length and/or changes to elements in that array)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment