A lightweight template library for the DOM.
Use TwoBits.js is easy!
<!DOCTYPE html>
<html>
<head>
<title>My Awesome Page</title>
<script src="twobits.js"></script><!-- Include TwoBits -->
</head>
<body>
<section id="dynamic">
<p>{{user.name}} works at {{user.company}}!</p>
</section>
<script>
// Use TwoBits!
var data = {
user: {
name: 'Josh',
company: 'Cinema6'
}
};
var updateDOM = tb.parse(document.getElementById('dynamic'));
updateDOM(data);
// The <p> above will now contain "Josh works at Cinema6!"
setTimeout(function() {
data.user.name = 'Evan';
updateDOM(data);
// Now (after three seconds) the <p> will contain "Evan works at Cinema6!"
}, 3000);
<script>
</body>
<html>
- Parameters:
- root (
Element
): A DOM element to parse. - options optional (
Object
): May contain the following properties:- context (any): A value that will be passed as the second argument to each directive
parseFn
. - filter (
Function
): If provided, this function will be invoked recursively with each child of theroot
. If the filter returns a falsy value, theNode
and all of its children will not be parsed.
- context (any): A value that will be passed as the second argument to each directive
- root (
- Returns:
- compile(context) (
Function
): A function that, when called, will update theroot
with providedcontext
data
- compile(context) (
- Parameters:
-
matcher (
String
): CSS selector that will determine theElement
s to which the directive will be applied. -
parseFn (
Function
): A function that will invoked for eachElement
that matchesmatcher
with theElement
andoptions.context
(passed totb.parse()
if provided) whentb.parse()
is invoked.parseFn
should return aFunction
,compile
, that will be invoked with aFunction
,get
, whenever the compileFunction
returned bytb.parse
is invoked. TheFunction
,get
, accepts aString
that can look-up property values on thecontext
using the same algorithm as curly braces in tempaltes. Here is an example of a directive that hides/shows anElement
:tb.directive('[data-show]', function(element) { var prop = element.getAttribute('data-show'); return function(get) { if (get(prop)) { element.style.display = 'none'; } else { element.style.display = ''; } }; });
<div id="example" data-show="should.show">Hello world!</div>
var compile = tb.parse(document.getElementById('example')); compile({ should: { show: true } }); // Element will be shown. compile({ should: { show: false } }); // Element will be hidden.
-
- Returns:
- tb: The twobits object, to enable a chaining API
Clears any global twobits state, most notably any registered directives.