From b060b5eb09a8c682cd53a1991c80162f8b29404d Mon Sep 17 00:00:00 2001 From: DarkWiiPlayer Date: Sun, 26 Dec 2021 17:45:17 +0100 Subject: [PATCH] Add listener.text helper --- listener.js | 12 ++++++++++++ listener.md | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/listener.js b/listener.js index e64d682..9b63d1e 100644 --- a/listener.js +++ b/listener.js @@ -57,4 +57,16 @@ export const bindContent = (listener, prop="value", target=document.createTextNo 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 diff --git a/listener.md b/listener.md index b3e6719..017e7e6 100644 --- a/listener.md +++ b/listener.md @@ -15,6 +15,24 @@ listener.listen(prop) // 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 bindContent(listener, "value") // Returns a text node with listener.value as its content