2015-12-20 116 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