Fetch data with promises and feed handlebars.
Fetch data with promises and feed handlebars.
by onigetoc
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.3/handlebars.min.js"></script>
<script id="PostsTempl" type="text/x-handlebars-template">
{{#each posts}}
<li class="item-handlebars">{{body}}</li>
{{/each}}
</script>
<div>
<ul id="posts">
<li class="item">I am an item</li>
</ul>
</div>
<button id="fetch-data">Fetch Data</button>
CSS
.item
{
color: red;
}
.item-handlebars
{
color: grey;
}
.big-font
{
font-size: 20px;
}
JavaScript
var myTemplate = Handlebars.compile($("#PostsTempl").html());
$('#fetch-data').on('click', function(){
fetchData()
.then(function(data){
console.log(data);
var posts = {posts: data};
$("#posts").append(myTemplate(posts));
return true;
})
.then(function(result){
goLookForDataAttributes();
})
.fail(function (reason) {
if (reason !== '') {
alert('Something went wrong:' + reason);
}
});
});
function goLookForDataAttributes()
{
$('#posts li.item-handlebars').each(function (index, item) {
$(item).addClass('big-font');
});
alert('all the attributes are ok!');
}
function fetchData()
{
var deferred = $.Deferred();
$.ajax({
type: 'GET',
dataType: 'json',
url: '//testapi.nsevenit.co.uk/api/test/posts/1/20',
data: {},
beforeSend: function (xhr) {
},
success: function (jsonData) {
if (jsonData) {
deferred.resolve(jsonData);
} else {
deferred.reject('');
}
},
complete: function () {
},
error: function (req, status, error) {
var errorMessage = (error.message) ? error.message : error;
deferred.reject(errorMessage);
}
});
return deferred.promise();
}