Generate views from JS easy peasy with dom()
. See demos:
pass: node value
returns: DOM node
var checkbox = dom({
// specify element name
el: 'input',
// set attributes
type: 'checkbox',
// set JS properties
_checked: true
// listen to events:
on_change: function() {
console.log(this.checked);
}
});
pass: array of node values
returns: document fragment
var docFrag = dom([
{ el: 'li', text: 'Milk' },
{ el: 'li', text: 'Butter' },
{ el: 'li', text: 'Juice' }
]);
document.querySelector('.shopping-list').appendChild(docFrag);
All the properties we are using in our plain object node values to render new elements can also be used to modify existing elements. This includes adding kids, event listeners, or classes; setting HTML attributes or an element's text; and setting JS properties. Let's modify the above example to stick our list items in an existing list using DOM Builder:
var shoppingList = dom({
el: document.querySelector('.shopping-list'),
kids: [
{ el: 'li', text: 'Milk' },
{ el: 'li', text: 'Butter' },
{ el: 'li', text: 'Juice' }
]
});
Set the kids
property to an array of node values
var label = dom({
el: 'label',
kids: [checkbox, 'Satisfied?']
});
document.body.appendChild(label);
Get live DOM updates with Snoopy
-
include Snoopy before DOM builder
<script src="path/to/snoopy.js"></script>
-
stick data in a Snoopy instance
var counter = Snoopy({count: 0});
-
live-bind data with Snoopy's
counter.snoop()
var button = dom({ el: 'button', text: counter.snoop('count'), on_click: function() { counter.set('count', counter.count + 1); } });
Node values can be any of the following:
- plain object: renders an element
- string or number: renders a text node
- DOM node without parent: renders the existing node
- array of node values: renders a document fragment
- "snoopable" function (Snoopy makes this easy):
- should accept a callback
- call it right away passing a node value
- call it again whenever the node value should change
These are the properties available for plain object node values for rendering elements. All are optional. If el
is unspecified, the element type defaults to 'div'.
el
- If value is a string, an element will be created with that tag name.
- If value is a DOM node, the other properties in the object will modify that.
kids
(array of node values): child nodes to appendtext
(string): sets the text of the element_className
,_innerHTML
, etc. (non-function values or a snoopable function): JS properties to set on elementon_input
,on_click
, etc. (function or array of functions): event listener(s) to addclass_active
,class_flagged
, etc. (boolean or snoopable function): specify whether the element should have an 'active' class, 'flagged' class etc.