Mustache data binding
Simple data binding with Mustache templates.
Motivation
Web applications frequently need to reflect changes to model data in the
view presented to the user. This is commonly done with many calls to
document.querySelector
, followed by attribute assignments.
// Model data.const user = name: 'Hubot' login: 'hubot' avatar: 'https://github.com/hubot.png'; // Display the model in the view.const link = document;link;link; const image = link;image;imagesrc = useravatar;
When the user
model data changes, all elements that depend on those values
must be found and reassigned. This style becomes difficult to maintain
as the number of templates and models grows. And design changes
to the markup require a careful inspection of the corresponding JavaScript
selectors to ensure they stay in sync.
So while an ad hoc solution works well as a starting point, we often want a reusable pattern as an app becomes more complex.
Data binding
One solution is to apply the Model-view-controller design pattern and bind the view (DOM nodes) as observers of model data. When the model changes, it notifies the observers, and updated values appear in the page.
This library provides one-way data binding: data flows from the model into the
view, as in MVC. Some other frameworks implement two-way data binding,
propagating changes in the view, typically from an <input>
element or
click
event, directly back into the model.
One-way data binding prescribes no method of moving view changes into the model, but a representative controller looks like the following example.
// The controller in one-way data binding.const input = document;input;
Usage
Store markup templates in the page with a unique data-name
attribute.
{{ user.name }}
Bind a model object—Mustache calls this a context—to a template.
; const context = id: 42 user: name: 'Hubot' login: 'hubot' url: 'https://github.com/hubot' avatar: 'https://github.com/hubot.png?size=460' ; // Create a single template function using its data-name.const avatar = ; // Build a new DocumentFragment from the template, bound to the model data.const fragment = ; // Display the new fragment in the page.documentbody; // Sometime later the model data changes, and the view is updated.contextusername = 'Bender';
Any JavaScript object may be used as the template's rendering context.
Limitations
This is a minimally viable Mustache parser, and only the {{ }}
stache syntax
is currently supported. As browser support for Proxy
improves, it can be used to observe Array
mutations and implement
the {{#}} {{/}}
iterator section syntax.
Development
npm install
npm test
Alternatives
A sample of full-fledged JavaScript data binding frameworks.
License
Distributed under the MIT license. See LICENSE for details.