Instantly share code, notes, and snippets.

Embed
What would you like to do?
Typescript Object property binding.
function BindFunc(tar:object,property:string,f:(v:any)=>void){
var property_emit = BIND_EMITTER(property);
if(tar.hasOwnProperty(property_emit)){
tar[property_emit].push(f);
}
else{
BindSetup(tar,property);
tar[property_emit].push(f);
}
}
function BindTwoWay(property:string,tar1:object,tar2:object){
BindFunc(tar1,property,(v)=>tar2[property] =v);
BindFunc(tar2,property,(v)=>tar1[property] =v);
}
function BIND_EMITTER(p:string){
return '_bind_' + p;
}
function BindSetup(tar: object, property: string) {
var property_emit = BIND_EMITTER(property);
if(tar[property_emit] != null) return;
tar[property_emit] = [];
var emitter = tar[property_emit];
var descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(tar), property);
if (descriptor != null && descriptor.set != null && descriptor.get != null) {
var getter = descriptor.get;
var setter = descriptor.set;
Object.defineProperty(tar, property, {
get: function () {
return getter.call(this);
},
set: function (v: any) {
let curv = getter.call(this);
if(curv != v){
setter.call(this, v);
emitter.forEach(f => f(v));
}
}
})
}
else {
var val = tar[property];
var property_bind = '_bind_' + property+'_p';
tar[property_bind] = val;
Object.defineProperty(tar, property, {
get: function () {
return this[property_bind];
},
set: function (v: any) {
let curv = this[property_bind];
if(curv != v){
this[property_bind] = v;
emitter.forEach(f => f(v));
}
}
})
}
}
class ClassA{
public p:number = 10;
}
class ClassB{
private m_p:number =10;
public get p():number{
return this.m_p;
}
public set p(v:number){
this.m_p = v;
}
}
var a = new ClassA();
var b = new ClassB();
BindFunc(a,'p',(v)=>{
console.log('a:'+v);
});
BindFunc(b,'p',(v)=>{
console.log('b:'+v);
});
a.p = 11;
b.p = 17;
BindTwoWay('p',a,b);
a.p = 15;
console.log('>b:'+b.p);
b.p = 25;
console.log('>a:'+a.p);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment