Skip to content

Instantly share code, notes, and snippets.

@vmysla
Created September 24, 2014 20:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vmysla/f33a50f802c1e8a8c45f to your computer and use it in GitHub Desktop.
Save vmysla/f33a50f802c1e8a8c45f to your computer and use it in GitHub Desktop.
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.js"></script>
<script>
(function Templify(undefined) {
var models = {};
function replace(template, pattern, value){
var expression = new RegExp('\\['+pattern+'\\]');
return template = template.replace(expression, value);
}
var templify = function(name, model){
var model = templify.models[name] = model || templify.models[name] || {};
if(arguments.length==1) return model;
$('script[type="text/templify"]').filter('[data-src="'+name+'"]').each(function(){
var source = this;
var target = $('<div/>').insertAfter(source);
(function update(){
var template = source.innerText;
for(var attr in model) template = replace(template, attr, model[attr]);
if(target.html() != template){
target.html(template);
}
window.setTimeout(update, 500);
})()
});
}
templify.models = {};
window.templify = templify;
})();
$(function(){
templify('currentUser',{
name : 'Valery',
id : 1
});
templify('currentUser').name = "Valery";
});
</script>
<body>
<script type="text/templify" data-src="currentUser">
Hello <b>[name]</b>!
</script>
</body>
@valerysntx
Copy link

Ideal to teach juniors how data binding works.
Anyone for two-way data binding? (observables, dirty-checking digest loops, events.. etc.)

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