Saturday, October 18, 2014

Further Experiments with grunt-init


The examples on https://github.com/r3b/ConnectJS2014 walk through an iterative build up of tools node --> npm --> grunt --> express

Key tool seems to be the grunt-init task which works like an archetype builder,   using  a template it sets up a standard of config files for various steps
 - package.json  :  for all module dependencies
 - Gruntfile.js :  build, test, deploy tasks.

Get new templates by cloning the Git repository to your ~/.grunt-init directory.
Command to instantiate the new archetype should be run inside an empty directory, followed by npm to download dependencies, and lastly grunt to execute default tasks.
>grunt-init {templatename}
> npm install
> grunt

Have learned since then:
> grunt -h
   lists all available tasks with handy descriptions, so easy to find out what a template does.

Curious to see how best to handle grunt-init "mashups"  and combining of templates.  Since grunt-init is for empty directories only,  seems like you still need to then iterate by hand as your project grows... or install a bunch of fluff at first for when you think you will need it later.

And have tried a couple of grunt + express templates... none of which seem to just "run" off the bat...


Monday, September 15, 2014

Fun with JS scope and closure : Sep 15 ATL.JS Chris Aquino

Inspired from tonights ATL.JS talk

Closure and the for loop problem:  If you really like 10
for(i=0; i < 10; i++){
setTimeout( function(){
console.log("i is " + i);}, 10);

}
Javascript is A) Lazy and B) Single Threaded.  So....  contrary to what you want:  For loop executes in the thread,  AND then the  i inside the closure function executes and sees that i now = 10 (last value).

Scope is a matter of perspective:  if you prefer undefined instead of 10
for(i=0; i < 10; i++){
setTimeout( function(i){
console.log("i is " + i);}, 10);

}
So now,  i is an argument, and it's not assigned when the function is created.  It stays undefined.

And even explicit assignment doesn't help.  The y here is part of the for loop,  so gets assigned 9 times, then function executes:
for(i=0; i < 10; i++){
var y = i;
setTimeout( function(){
console.log("i is " + y);}, 10);

}
So for readable, manageable scope: create a function to create the function, so that each execution of the loop the iterator value is captured to a isolated scope and preserved until later.

function showI(i){
function show() {
console.log("i is "+ i);
};
return show;
}

for(i=0; i < 10; i++){
setTimeout( showI(i), 10);

}