Skip to content

Instantly share code, notes, and snippets.

@aheinze
Last active August 29, 2015 14:19
Show Gist options
  • Save aheinze/f273656f6107d6c27f3e to your computer and use it in GitHub Desktop.
Save aheinze/f273656f6107d6c27f3e to your computer and use it in GitHub Desktop.
riot.view.js - inline compiled view templates
/**
USAGE:
<script src="riot+compiler.min.js"></script>
<script src="riot.view.js"></script>
<script type="riot/tag" src="my-tag.tag"></script>
<div riot-view>
Random: { random }
<my-tag></my-tag>
<button onclick="{ updaterandom }">Update Random</button>
<script type="view/script">
this.random = Math.random();
updaterandom() {
this.random = Math.random();
}
</script>
</div>
**/
(function(riot, d){
if (!riot || !riot.compile) {
return;
}
d.writeln('<style>[riot-view]{display:none}</style>');
d.writeln('<script type="riot/tag"></script>');
riot.initViews = (function(views, view, vid, tag, ele, i) {
return function() {
views = d.querySelectorAll('[riot-view]');
for (i=0;i<views.length;i++) {
view = views[i];
vid = viewuid();
tag = ("<"+vid+">\n" + view.innerHTML + "\n</"+vid+">").replace(' type="view/script"', '');
ele = d.createElement(view.tagName);
copyattrs(view, ele);
riot.compile(tag);
view.parentNode.insertBefore(ele, view);
view.parentNode.removeChild(view);
riot.mount(ele, vid);
}
};
})();
d.addEventListener('DOMContentLoaded', function(event) {
riot.compile(riot.initViews);
});
function copyattrs(src, target) {
for (var i = 0, atts = src.attributes, n = atts.length; i < n; i++) {
if (atts[i].name == 'riot-view') continue;
target.setAttribute(atts[i].name, atts[i].value);
}
}
function viewuid() {
return 'view-xxxxxxxx'.replace(/[x]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
})(riot, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment