Extend skooma.text function to support template strings
This commit is contained in:
parent
4a473df213
commit
47969d4c42
2 changed files with 23 additions and 1 deletions
15
skooma.js
15
skooma.js
|
@ -99,4 +99,17 @@ export const handle = fn => event => { event.preventDefault(); return fn(event)
|
|||
export const html = nameSpacedProxy({nameFilter: name => name.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()})
|
||||
export const svg = nameSpacedProxy({xmlns: "http://www.w3.org/2000/svg"})
|
||||
|
||||
export const text = (data="") => document.createTextNode(data)
|
||||
const textFromTemplate = (literals, items) => {
|
||||
const fragment = new DocumentFragment()
|
||||
for (const key in items) {
|
||||
fragment.append(document.createTextNode(literals[key]))
|
||||
fragment.append(items[key])
|
||||
}
|
||||
fragment.append(document.createTextNode(literals.at(-1)))
|
||||
return fragment
|
||||
}
|
||||
|
||||
export const text = (data="", ...items) =>
|
||||
typeof data == "string"
|
||||
? document.createTextNode(data)
|
||||
: textFromTemplate(data, items)
|
||||
|
|
|
@ -48,8 +48,17 @@ text()
|
|||
// Defaults to empty string instead of erroring
|
||||
text(null)
|
||||
// Non-string arguments still error
|
||||
|
||||
text`Hello, World!`
|
||||
// returns a new document fragment containing the text node "Hello, World!"
|
||||
text`Hello, ${user}!`
|
||||
// returns a document fragment containing 3 nodes:
|
||||
// "Hello, ", the interpolated value of `user` and "!"
|
||||
```
|
||||
|
||||
When used with templates, `text` tries to append any interpolated values into
|
||||
the document fragment as is and without checking them.
|
||||
|
||||
## bind
|
||||
|
||||
This function offers a generic mechanism for binding elements to dynamic state.
|
||||
|
|
Loading…
Reference in a new issue