Skip to content

Instantly share code, notes, and snippets.

@shawndumas
Last active July 26, 2023 10:07
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save shawndumas/9b7cc2df195e3e1518fb to your computer and use it in GitHub Desktop.
Save shawndumas/9b7cc2df195e3e1518fb to your computer and use it in GitHub Desktop.
Pure Handlebars Bound Helper via Object.observe
<html>
<head>
<style>
b {
font-weight: normal;
}
</style>
<script src="http://cdn.jsdelivr.net/handlebarsjs/2.0.0/handlebars.js"></script>
</head>
<body>
<div/>
<script id="bound-template" type="text/x-handlebars-template">
going up?&nbsp;{{bound floor}}<br/>
message:&nbsp;{{bound message}}
</script>
<script>
Handlebars.registerHelper('bound', (function () {
var uniq = 0;
return function (value) {
var id = '__uniq__' + (++uniq),
name;
for (name in this) {
if (this.hasOwnProperty(name)) {
if (this[name] === value) {
break;
}
}
}
Object.observe(this, function (changes) {
document.getElementById(id).innerText = changes
.filter(function (change) {
return change.name === name;
})
.shift()
.object[name];
});
return new Handlebars.SafeString(
'<b id="' + id + '">' +
value +
'</b>'
);
};
}()));
var o = { floor: 1, message: 'inital' },
t = Handlebars.compile(document.getElementById('bound-template').innerHTML);
document.querySelector('div').innerHTML = t(o);
window.setInterval(function () { o.floor += 1; }, 1000);
</script>
</body>
</html>
@notyoyoma
Copy link

Hey, how did this perform? Specifically, would it perform well with ~200 observes updating ~20 templates simultaneously?

Context: I'm building a lightweight game in html/js/css and I really like the handlebars format, but need one-way performant data binding. I've looked into Ember React Angular Polymer Rivet and about 10 other smaller frameworks, but they're all too heavy for what I want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment