Cookie Notice

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


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.

var accordion_request = {} ;
accordion_request.m_path    = '/dev/dave' ;
accordion_request.templates = {} ;
accordion_request.template_fetch = []
accordion_request.template_fetch.push( 'div_request' ) ;
accordion_request.template_fetch.push( 'div_sample' ) ;
accordion_request.template_fetch.push( 'div_final' ) ;

accordion_request.get_templates = function ( ) {
    for ( var t in accordion_request.template_fetch ) {
        var template = accordion_request.template_fetch[t] ;
        var name = [ template , 'm' ].join( '.' )
        var url = [ accordion_request.m_path , name ].join('/') ;
        console.log( template ) ;
        console.log( name ) ;
        console.log( url ) ;
        $.get( url , function ( data ) {
            console.log( ': ' + url ) ;
            accordion_request.templates[template] = data ;
            }  ) ;

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:
: /dev/dave/div_final.m
: /dev/dave/div_final.m
: /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