Skip to content

Instantly share code, notes, and snippets.

@mlhaufe
Last active July 3, 2020 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlhaufe/51920d8f5f515dcf9775485a48bc5900 to your computer and use it in GitHub Desktop.
Save mlhaufe/51920d8f5f515dcf9775485a48bc5900 to your computer and use it in GitHub Desktop.
TypeScript databinding
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