Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Created November 23, 2015 00:56
Show Gist options
  • Save james2doyle/659c6f8d433a2b8f841e to your computer and use it in GitHub Desktop.
Save james2doyle/659c6f8d433a2b8f841e to your computer and use it in GitHub Desktop.
Simulacra.js example using AJAX loaded data
<template id="tasks">
<h3 class="header"></h3>
<ul>
<li class="task"></li>
</ul>
</template>
<div id="app">
<!-- the rendered content will be thrown in here -->
</div>
// this assumes you have included simulacra.js
var bind = window.simulacra;
var fragment = document.getElementById('tasks').content;
// simple wrapper for finding the elements by class
window.$ = function(selector) {
return fragment.querySelector(selector);
};
var bindings = bind(fragment, {
header: bind($('.header')),
tasks: bind($('.task'))
});
// may require the whatwg-fetch polyfill
fetch('tasks.json')
.then(function(response) {
return response.json();
}).then(function(res) {
var output = bind(res.data, bindings);
// throw in the rendered content
document.getElementById('app').appendChild(output);
}).catch(function(err) {
console.error(err);
});
{
"data": {
"header": "My Task List",
"tasks": [
"Task 1",
"Task 2",
"Task 3",
"Task 4",
"Task 5",
"Task 6",
"Task 7",
"Task 8",
"Task 9",
"Task 10",
"Task 11",
"Task 12",
"Task 13",
"Task 14",
"Task 15",
"Task 16",
"Task 17",
"Task 18",
"Task 19",
"Task 20"
]
}
}
@gr0uch
Copy link

gr0uch commented Nov 24, 2015

It would be nice to store res.data somewhere so that the list can be mutated :)

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