2012-12-22 99 views
0

我粘貼在這裏的整體功能,並順便我用這個腳本小鬍子模板庫,但不是在這個問題必要的:有沒有更簡單的方法來使用Ajax進行函數調用?

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(); 
      } 
     }); 
    } 

我不能讓它短並刪除重複的代碼,因爲我不能在Ajax成功分配本地變量,因爲它是異步的。我已經在互聯網上游蕩了大約15個小時。但仍然沒有運氣。

我該如何刪除重複的代碼並縮短這個東西?

回答

1
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); 
} 
+0

您是否故意沒有將參數添加到setOutput和doJSON? –

+1

這兩個參數都選擇映射$ .getJSON和$ .get成功函數。 – closure

1

好,功能也沒有,如果你有重複的代碼:)

只是爲了踢,這裏是你如何有一個:

tmplReplaceContent : function(json, tmpl, target){ 

    function render(tmplOut) { 
     template = tmplOut; 
     var content = Mustache.render(template, view); 
     $(target).html(content).hide().fadeIn(); 
    } 

    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', render); 
     } else { 
      render(); 
     } 
// Etc... 

縮短東西相當多,對吧?

相關問題