Add bind function to listener.js

This commit is contained in:
Talia 2021-11-23 16:30:11 +01:00
parent 658608a405
commit 945736b9a9
2 changed files with 28 additions and 1 deletions

View File

@ -8,7 +8,7 @@ Example:
l.contract = new Contract()
*/
export default (target={}) => {
export const listener = (target={}) => {
let callbacks = new Map()
function listen(prop, callback) {
if ("object" == typeof prop && "forEach" in prop) {
@ -38,3 +38,20 @@ export default (target={}) => {
})
return proxy
}
export const bind = (listener, prop, target=document.createTextNode(""), filter) => {
const run = data => {
data = filter
? filter(data)
: data
if ("innerText" in target)
target.innerText = data
else
target.data = data
}
listener.listen(prop, run)
run(listener[prop])
return target
}
export default listener

View File

@ -15,6 +15,16 @@ listener.listen(prop)
// Removes all callbacks from a given property
```
```js
bind(listener, "value")
// Returns a text node with listener.value as its content
// that will change whenever the value is changed
bind(listener, "value", html_element)
// Binds an existng HTML or Text node
bind(listener, "value", html_element, value => value.toUpperCase())
// Filters the value through a function before setting it
```
## Example
```js