Last active
December 29, 2017 02:33
-
-
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
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
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); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)