Created
June 14, 2013 13:57
-
-
Save davepermen/5781996 to your computer and use it in GitHub Desktop.
Tiny Async Handler in JS
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
var get = function (path, callback) { | |
var xhr = new XMLHttpRequest(); | |
xhr.onload = function () { | |
if (this.status === 200) { | |
callback(this.responseText); | |
} | |
}; | |
xhr.open('get', path); | |
xhr.send(); | |
}; | |
var articleSection = document.querySelector('#articles'); | |
whenall(function (on) { | |
get(window.location.pathname, on('model')); | |
get('/template/articles.html', on('template')); | |
setTimeout(on('timeout'), 2000); | |
}, function (data) { | |
articleSection.innerHTML = Mustache.to_html(data.template, JSON.parse(data.model)); | |
}); |
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
var whenall = function (begin, end) { | |
var index = 0; | |
var results = {}; | |
var on = function (name) { | |
++index; | |
return function (data) { | |
--index; | |
results[name] = data; | |
if (index === 0) { | |
end(results); | |
} | |
}; | |
}; | |
begin(on); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment