Add listener.text helper

This commit is contained in:
Talia 2021-12-26 17:45:17 +01:00
parent cf116753a8
commit b060b5eb09
No known key found for this signature in database
GPG key ID: AD727AD22802D0D6
2 changed files with 30 additions and 0 deletions

View file

@ -57,4 +57,16 @@ export const bindContent = (listener, prop="value", target=document.createTextNo
return target return target
} }
export const text = (listener, prop) => {
if (prop) {
const node = document.createTextNode(listener[prop])
listener.listen(prop, data => node.data = data)
return node
} else {
return new Proxy(listener, {
get: (target, prop, receiver) => text(listener, prop)
})
}
}
export default listener export default listener

View file

@ -15,6 +15,24 @@ listener.listen(prop)
// Removes all callbacks from a given property // Removes all callbacks from a given property
``` ```
```js
text(listener, "property")
// Returns a text node bound to listener.property
text(listener)
// Returns a text node proxy for the listener
text(listener).property
// Same as first example
```
When called with two arguments, this function returns a new text node that will
automatically update to reflect the given property on the listener.
When called with only the listener, it creates a proxy object that, when
indexed, returns the result of calling `text` on the listener and the indexed
property name.
Note that repeatedly indexing the proxy will return a new text node each time.
```js ```js
bindContent(listener, "value") bindContent(listener, "value")
// Returns a text node with listener.value as its content // Returns a text node with listener.value as its content