Skip to content

Instantly share code, notes, and snippets.

@wulymammoth
Created July 2, 2014 21:21
Show Gist options
  • Select an option

  • Save wulymammoth/c1fbc9d25a74b009f031 to your computer and use it in GitHub Desktop.

Select an option

Save wulymammoth/c1fbc9d25a74b009f031 to your computer and use it in GitHub Desktop.
One-way data-binding
function bind(expr, data, el){
el.render = render.bind(null, expr, data, el);
return on('squirt.els.render', function(){
el.render();
});
};
function render(expr, data, el){
var match, rendered = expr;
expr.match(/{{[^}]+}}/g).map(function(match){
var val = data[match.substr(2, match.length - 4)];
rendered = rendered.replace(match, val == undefined ? '' : val);
});
el.textContent = rendered;
};
function on(bus, evts, cb){
if(cb === undefined){
cb = evts;
evts = bus;
bus = document;
}
evts = typeof evts == 'string' ? [evts] : evts;
var removers = evts.map(function(evt){
bus.addEventListener(evt, cb);
return function(){
bus.removeEventListener(evt, cb);
};
});
if(removers.length == 1) return removers[0];
return removers;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment