Created
April 21, 2016 05:22
-
-
Save resistdesign/4be5a25bd38ad235dcf3c7a81aac92e3 to your computer and use it in GitHub Desktop.
Bindable Demo
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 Bindable(ClassRef, onChangeMethodName){ | |
class BindableClass{ | |
constructor(...args){ | |
const instance = new (ClassRef.bind(this))(...args); | |
for(const k in instance){ | |
if(instance.hasOwnProperty(k)){ | |
const initialValue = instance[k]; | |
const privatePropertyName = `_${k}`; | |
instance[privatePropertyName] = initialValue; | |
Object.defineProperty(instance, k, { | |
get: function(){ | |
return instance[privatePropertyName]; | |
}, | |
set: function(value){ | |
if(instance[privatePropertyName] !== value){ | |
const oldValue = instance[privatePropertyName]; | |
instance[privatePropertyName] = value; | |
if( | |
typeof onChangeMethodName === 'string' && | |
ClassRef.prototype.hasOwnProperty(onChangeMethodName) && | |
instance[onChangeMethodName] instanceof Function | |
){ | |
const onChange = instance[onChangeMethodName]; | |
onChange(k, value, oldValue); | |
} | |
} | |
} | |
}); | |
} | |
} | |
return instance; | |
} | |
} | |
return BindableClass; | |
} | |
class Comp { | |
constructor(){} | |
m = 'p'; | |
h = undefined; | |
help(...args){ | |
console.log(JSON.stringify(args, null, '\t')); | |
} | |
} | |
const BC = Bindable(Comp, 'help'); | |
const bc = new BC(); | |
bc.m = 'T'; | |
bc.h = 'L'; | |
console.log('\n\n\n'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Automatically track the changes of all pre-initialized properties of a class.