Cookie Notice

As far as I know, and as far as I remember, nothing in this page does anything with Cookies.

2014/01/29

Coming to Terms with Javascript's Not-Quite-Procedural Nature

I'm creating a web application. I've written HTML code on the server before and have decided templates are best, because whatever language, writing code that generates HTML is always worse than making a template that has holes you can fill with your data. This is why I now love Perl's Template Toolkit.

Funny thing is, making the code client-side doesn't make it much better. For now, I'm using Mustache.

There are many things you can easily do in JavasScript, but multi-line variables are not pretty in JavaScript, so it's far better to have external templates and import them. This is my current code to import a list of templates, which so far are div_request.m, div_sample.m and div_final.m.

  1. var accordion_request = {} ;  
  2. accordion_request.m_path    = '/dev/dave' ;  
  3. accordion_request.templates = {} ;  
  4. accordion_request.template_fetch = []  
  5. accordion_request.template_fetch.push( 'div_request' ) ;  
  6. accordion_request.template_fetch.push( 'div_sample' ) ;  
  7. accordion_request.template_fetch.push( 'div_final' ) ;  
  8.   
  9. accordion_request.get_templates = function ( ) {  
  10.     for ( var t in accordion_request.template_fetch ) {  
  11.         var template = accordion_request.template_fetch[t] ;  
  12.         var name = [ template , 'm' ].join( '.' )  
  13.         var url = [ accordion_request.m_path , name ].join('/') ;  
  14.         console.log( template ) ;  
  15.         console.log( name ) ;  
  16.         console.log( url ) ;  
  17.         $.get( url , function ( data ) {  
  18.             console.log( ': ' + url ) ;  
  19.             accordion_request.templates[template] = data ;  
  20.             }  ) ;  
  21.         }  
  22.     }  

Do you see the problem?

JavaScript does not block. So, we convert div_request to div_request.m to /dev/dave/div_request.m, then we set the jQuery $.get() off to get that url, then we convert div_sample to div_sample.m to /dev/dave/div_sample.m and set that off to $.get(), then jump back to div_final.

By the time $.get() starts working, url is "/dev/dave/div_final.m", so we get a console log that looks like:
  1. div_sample  
  2. div_sample.m  
  3. /dev/dave/div_sample.m  
  4. div_request  
  5. div_request.m  
  6. /dev/dave/div_request.m  
  7. div_final  
  8. div_final.m  
  9. /dev/dave/div_final.m  
  10. : /dev/dave/div_final.m  
  11. : /dev/dave/div_final.m  
  12. : /dev/dave/div_final.m  

I now believe I need to write a function that takes url and gets and writes it, so that it has it's own scoped url rather than using the one in get_templates(). We will see.

No comments:

Post a Comment