Search code examples
javascriptdryshortest-pathnon-repetitive

Is there any shorter way to do function calls with Ajax in it?


I am pasting the whole function in here, and by the way I used the mustache templating library in this script, but that is not necessary in the question:

tmplReplaceContent : function(json, tmpl, target){
    var regex = new RegExp("\{{[a-zA-Z\.\_]*\}}");
    var template = '';
    var view = '';
    /* json -> check if object */
    if (typeof json == 'object') {
        view = json;
        if(!regex.test(tmpl)){
            /* get mustache tmpl from the path */
            $.get(msi.vars.tmpl_url + tmpl + '.mustache', function(tmplOut){
                template = tmplOut;
                var content = Mustache.render(template, view);
                $(target).html(content).hide().fadeIn();
            });
        } else {
            template = tmpl;
            var content = Mustache.render(template, view);
            $(target).html(content).hide().fadeIn();
        }
    } else {
        /* getJSON from the path */
        $.getJSON(msi.vars.base_url + json, function(jsonOut){
            view = jsonOut;
            if(!regex.test(tmpl)){
                /* get mustache tmpl from the path */
                $.get(msi.vars.tmpl_url + tmpl + '.mustache', function(tmplOut){
                    template = tmplOut;
                    var content = Mustache.render(template, view);
                    $(target).html(content).hide().fadeIn();
                });
            } else {
                template = tmpl;
                var content = Mustache.render(template, view);
                $(target).html(content).hide().fadeIn();
            }
        });
    }

I wasn't able to make it short and remove the repetitive code because I cannot assign local variables in the Ajax success for it is asynchronous. I have wandered in the internet for about 15 hrs. But still no luck.

How can I remove repetitive code and make this thing shorter?


Solution

  • tmplReplaceContent : function(json, tmpl, target) {
    
      var regex = new RegExp("\{{[a-zA-Z\.\_]*\}}"),
          view = '';
    
      function setOutput(template) {
          var content = Mustache.render(template, view);
          $(target).html(content).hide().fadeIn();
      }
    
      function doJSON(json) {
          view = json;
          if(!regex.test(tmpl)){
              /* get mustache tmpl from the path */
              $.get(msi.vars.tmpl_url + tmpl + '.mustache', setOutput);
          } else {
              setOutput(tmpl);
          }
      }
    
      /* json -> check if object */
      if (typeof json === 'object') {
        doJSON(json);
      } else {
          /* getJSON from the path */
          $.getJSON(msi.vars.base_url + json, doJSON);
    }