Created
November 23, 2015 00:56
-
-
Save james2doyle/659c6f8d433a2b8f841e to your computer and use it in GitHub Desktop.
Simulacra.js example using AJAX loaded data
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
<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 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
// 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); | |
}); |
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
{ | |
"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" | |
] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It would be nice to store
res.data
somewhere so that the list can be mutated :)