DOMGlue is a simple, unobtrusive view layer that utilizes the DOM instead of using a custom template language.
DOMGlue can render a part of the live DOM or use template strings containing HTML or XML.
Elements with variable content are marked with a data-key
attribute. Each data-key
attribute has as its value a key in the data which is used to render the template or update
the DOM.
The data-key
's can form a hierarchy. For example, take the following DOM snippet:
<div data-key="item">
<h2 data-key="title">???</h2>
<div data-key="body">...</div>
</div>
This snippet can be populated with the following data:
{
item: {
title: "Foo",
body: "Lorem ipsum dolor sit amet."
}
}
The result will be:
<div data-key="item">
<h2 data-key="title">Foo</h2>
<div data-key="body">Lorem ipsum dolor sit amet.</div>
</div>
Of course you can also manipulate attributes. This is done by prepending a key in the data
with an @
character. So if we have this DOM fragment:
<input data-key="input" name="?" type="text" placeholder="?" value="?" />
We can fill the attributes with data such as this:
{
input: {
"@name": "myInput",
"@placeholder": "Insert text",
"@value": "Default value"
}
}
Of course it also works with both attributes and sub-keys:
<div data-key="item">
<div data-key="title"></div>
</div>
{
item: {
"@class": "some-class",
"title": "The title!"
}
}
This results in:
<div data-key="item" class="some-class">
<div data-key="title">The title!</div>
</div>
npm install domglue
var glue = require("domglue");
var view = glue.live(element)
Creates a DOMGlue view for an element. Returns an object with the following methods.
view.update(data)
Updates the view with data
.
view.render(data)
Updates the view with data
and removes all elements with keys that are not contained
within data
.
view.set(key, value, raw)
Sets the value for one key. If more than one element bears the key, all the elements
are changed. If raw
is given and set to true
, the values will not be escaped.
This can be useful if you want to insert HTML, but you need to be careful about XSS.
view.set(values, raw)
Sets many keys. The values
property maps keys to values. If raw
is given and is set
to true
, values will not be escaped!
view.setRaw(key, value)
view.setRaw(values)
Shorthand for using the set
method with raw values.
view.get(selector)
Returns the value for a key. If more than one element bears the key, only the first value is
returned. The parameter selector
can be either just a key or a combination of a key and
an attribute:
some_key/some_attribute
view.getAll(selector)
Same as the get
method, but returns an array containing the values of all elements/attributes
with the given key.
view.destroy()
Destroys the view and cleans up references to the DOM element.
var template = glue.template(content)
Creates a DOMGlue template.
template.render(data)
Renders the template using data
and returns the result as a string.
Removes elements that with keys that don't exist in data
.