HTML document. For example, in order to bind src to url in the template <img src=“{{url}}”> the mustache needs to know that it’s in an attribute value. • Every time a template is rendered, it’s parsed from scratch via innerHTML. Can we do better? • String manipulations increase the pressure on the garbage collector*. * I haven’t checked this for myself.
{ var el0 = dom.createDocumentFragment(); dom.appendText(el0, 'Hello '); var el1 = dom.createElement('em'); dom.appendChild(el0, el1); dom.appendText(el0, '!\n'); return el0; } var cachedFragment = null; return function template(context, options) { • Creates a document fragment via a dom abstraction. • Doesn’t see the {{mustaches}}. Fragment program Hello <em>{{name}}</em>!
(cachedFragment === null) { cachedFragment = build(dom); } var fragment = dom.cloneNode(cachedFragment); var hooks = options && options.hooks; var helpers = options && options.helpers || {}; var morph0 = Morph.create(fragment.childNodes[1], -1, -1); hooks.content(morph0, 'name', context, [], { escaped: true }, he return fragment; }; • Calls the fragment program to build the fragment on the first run through. • Caches it and deep clones it on the next runs. Template program Hello <em>{{name}}</em>!
&& options.helpers || {}; var morph0 = Morph.create(fragment.childNodes[1], -1, -1); hooks.content(morph0, 'name', context, [], { escaped: true }, helpers); return fragment; }; • Uses Morphs to keep references to the boundary DOM nodes surrounding a mustache in the fragment that was just cloned. • Calls the content hook to fill in morph0 and possibly setup any streams. Hydration program Hello <em>{{name}}</em>!