Yo community! might need some insights here.. 🙂 I’m learning some more advance js-concepts. Im running this code but the result is not showing up as I was expecting..I can’t see the error…any idea? thanks!
<script type="text/javascript">
(function() {
var results, queue = [];
this.assert = function(pass, msg) {
var type = pass ? "PASS" : "FAIL";
var str = "<li class='" + type + "'><b>" +
type + "</b> " + msg + "</li>";
if ( queue )
queue.push( str );
else
results.innerHTML += str;
};
window.addEventListener("load", function() {
results = document.getElementById("results");
results.innerHTML = queue.join('');
queue = null;
});
// calling assert but it's not showing up the <li> with the message....( why? )
assert( true, "I always pass!" );
})();
</script>
The way this
assert()function works is that if it is called before the document load event has occurred any results are stored in thequeuearray: the conditionif (queue)will be true becausequeuerefers to the array.Then when the load handler runs it takes everything already in
queueand outputs it to theresultselement before settingqueueto null:Any calls to
assert()after the document load will then find thatif (queue)is false becausequeueis null, so then theelsewill be executed and any results will be output directly to theresultselement.In your code as shown, there is only one call to
assert()and it will occur before the document load handler has run.(Here’s a clunky demonstration of this – presses to the button will be after the load event: http://jsfiddle.net/JDFuR/1/)