Last active
July 26, 2023 10:07
-
-
Save shawndumas/9b7cc2df195e3e1518fb to your computer and use it in GitHub Desktop.
Pure Handlebars Bound Helper via Object.observe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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? {{bound floor}}<br/> | |
message: {{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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.