Skip to content

Instantly share code, notes, and snippets.

@resistdesign
Created April 21, 2016 05:22
Show Gist options
  • Save resistdesign/4be5a25bd38ad235dcf3c7a81aac92e3 to your computer and use it in GitHub Desktop.
Save resistdesign/4be5a25bd38ad235dcf3c7a81aac92e3 to your computer and use it in GitHub Desktop.
Bindable Demo
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');
@resistdesign
Copy link
Author

Automatically track the changes of all pre-initialized properties of a class.

@resistdesign
Copy link
Author

ES6+, Stage 0

@resistdesign
Copy link
Author

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