2015-12-20 34 views
-1

我試圖讓我的javascript代碼貼到模塊模式這我下面在這裏:模塊模式javascript不是函數?

http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript

這是我的代碼目前,沒有語法問題,除了運行時調用它說

loosetime.init()不是函數。

var loosetime = (function() { 
    var looseconfig = { 
     "format": "DD/MM/YY HH24:MM:SS.s", 
     "value": "DD/MM/YY 00:00.00", 
     "class": "input", 
     "delims": ['/', '-', '_', '.', '|', ',', ' ', ':'] 
    }; 

    function loosetime(a, b, c, d, e) { 
     var format = a; 
     var appendLoc = b; 
     var inputVal = c; 
     var inputName = d; 
     var inputClass = e; 
     var inputLength; 

     try { 
      if (typeof(format) == 'undefined') { 
       format = looseconfig.format; 
      } else { 
       format = parseDateTime(format); 
      } 

      try { 
       if (typeof(inputVal) == 'undefined') { 
        inputVal = looseconfig.value; 
       } 

       inputLength = inputVal.length - 2; 
       var input = document.createElement("input"); 
       input.setAttribute("name", inputName); 
       input.setAttribute("maxlength", inputLength); 
       input.setAttribute("size", inputLength); 
       input.setAttribute("value", inputVal); 
       input.setAttribute("type", "input"); 
       input.setAttribute("class", inputClass); 
       input.setAttribute("onkeypress", "dateTimeRules(event)"); 
       input.setAttribute("onclick", "resetCursorPos(event)"); 
       input.setAttribute("loosetime", format); 

       try { 
        var element = document.getElementById(appendLoc); 

        element.appendChild(input); 
       } catch (e) { 
        window.alert("Error, no Element given to append loosetime to.") 
       } 
      } catch (e) { 
       window.alert("Error, Value is invalid." + e.toString()); 
      } 
     } catch (e) { 
      window.alert("Error, Date format missing or invalid."); 
     } 
    } 

    // other code here ... 

    return { 
     init: loosetime() 
    } 

    // end private closure then run the closure 
    }); 

理想我只想loosetime工作,我不想顯式調用構造函數。

例如loosetime(「foo」,「bar」,「etc」,「yolo」,「123321」);

我不知道我在做什麼錯,我是否需要返回函數本身而不是別名?

+0

不知道爲什麼我會陷入低谷。 – kaleeway

回答

1

有兩件事是錯誤的。

首先您需要確保您的模塊是自調用匿名函數(SIAF),也就是馬上調用函數表達式(IIFE)。 您可以在此找到更多信息here

其次,您不能調用模塊內部的loosetime函數,因爲它不返回任何內容。您需要將init鍵的值作爲對loosetime函數的參考。現在

你可以打電話init和你的模塊內部的loosetime功能將被執行。

+1

感謝您的幫助! – kaleeway

3
return { 
    init: loosetime() 
} 

init返回值的調用loosetime(這是undefined,因爲該功能不具有return語句)。

如果要分配函數本身而不是調用它,請刪除()


你的第二個問題是,暴露模塊的模式要求你運行封閉

//end private closure then run the closure 
})(); 

儘管你的評論,你錯過了斷()那裏。

+0

我已經有了,請看底部的源代碼 – kaleeway

+1

@kaleeway請仔細閱讀答案。 – Oka

+0

@kaleeway - 我引用的代碼是從你的問題中提取的,所以你當然擁有它。該代碼是問題。閱讀其餘的答案,看看如何解決它。 – Quentin