Skip to content

Instantly share code, notes, and snippets.

@boydc2014
Last active December 6, 2018 12:10
Show Gist options
  • Save boydc2014/dfbe1af80ba9957960392b3096915635 to your computer and use it in GitHub Desktop.
Save boydc2014/dfbe1af80ba9957960392b3096915635 to your computer and use it in GitHub Desktop.
Show a more simple and native way to create a event system for change tracking, notification, validation ... etc
// this state is just a simple observer
class State {
constructor(public data: object) {
this.walk(data);
}
walk = (obj: Object) => {
this.data = obj;
for (let k in obj)
{
if (obj.hasOwnProperty(k))
{
let val = obj[k];
if (typeof val === "object")
{
new State(val);
}
this.convert(k, val);
}
}
}
convert = (key:string, val:any) => {
Object.defineProperty(this.data, key, {
enumerable: true,
configurable: true,
get: function(){
return val;
},
set: function(newVal) {
// you can fire events here
// you can check with validators here (validators is just event handler)
console.log("change event fired")
if (newVal === val) return ;
val = newVal;
new State(newVal);
}
});
}
}
var properties = {
profile: {
name: "",
age: 0
},
stars: [15]
};
var observer = new State(properties);
// note here we are reference "properties" not observer
// but you can simple do that by adding all the top-level property of "properties" to observer
// depends on which level you want to add event
properties.profile = {name: "Dong Lei", age: 28}; // change at top-level will trigger change event
properties.profile.name = "Dong Lei"; // change at bottom-level will also do that
properties.stars[0] = 28; // change in array avalue also fire event
// as you can image, list operations can also be supported here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment