Last active
July 3, 2020 22:50
-
-
Save mlhaufe/51920d8f5f515dcf9775485a48bc5900 to your computer and use it in GitHub Desktop.
TypeScript databinding
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(proto: any, name: PropertyKey) { | |
const desc = Object.getOwnPropertyDescriptor(proto, name) | |
delete proto.name | |
if ((proto['_dispatchEvent']) == undefined) { | |
Object.defineProperty(proto, '_dispatchEvent', { | |
value(event: Event) { | |
} | |
}) | |
} | |
Object.defineProperty(proto, `_${String(name)}`, { | |
value: undefined | |
}) | |
Object.defineProperty(proto, name, { | |
get() { | |
return this[`_${String(name)}`] | |
}, | |
set(value) { | |
const strName = String(name) | |
this[`_${strName}`] = value | |
this._dispatchEvent( | |
new CustomEvent(`update${strName}Value`, { | |
detail: {value} | |
}) | |
) | |
} | |
}) | |
} | |
class Person { | |
@Bindable | |
name: string | |
@Bindable | |
age: number | |
constructor(name: string, age: number) { | |
this.name = name | |
this.age = age | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment