Javascript模块化布局:如何从一个模块中调用另一个模块中定义的函数?
以下是javascript应用程序的模块化布局示例.我想开始在工作中使用这种结构.我正在努力弄清它是如何工作的,需要了解如何从另一个模块调用一个模块中定义的函数?这肯定是布局JavaScript繁重应用程序的最佳选择吗?
Below is an example of a modular layout of a javascript application. I want to start using such a structure for my work. I am struggling to get my head round how it works and need to understand how to call a function that is defined in one module from a different module? Is this definitely the bet way to layout a JavaScript heavy application?
window.MainModule = (function($, win, doc, undefined) {
var modules = {};
// -- Create as many modules as you need ...
modules["alerter"] = (function(){
var someFunction = function(){ alert('I alert first'); };
return {
init: someFunction
};
}());
modules["alerter2"] = (function(){
var someFunction = function(){ alert('I alert second'); };
return {
init: someFunction
};
}());
return {
init: function(){
for (var key in modules){
modules[key].init();
}
}
};
}(jQuery, this, document));
$(window.MainModule.init);
具有 RequireJS 的模块化:
Modularity with RequireJS:
module1.js
define( ["dependency"] , function( dep ){
return {
speak: function(){
alert( dep.message );
}
}
} );
dependency.js
define( {
message: "Hello world!"
} );
impl.js
if ( $(".someCssExpression").length ) {
require( [ "module1" ] , function( mod ){
mod.speak();
});
}
index.html
...
<script src="require.js" data-main="impl"></script>
...
您的文件结构将是模块化的. 您的实现将是模块化的. 而且没有笨拙的命名空间或怪异的结构使它看起来井井有条.
Your file structure will be modular. Your implementation will be modular. And no clunky namespacing or weird constructs to make it feel organised.
需要一些习惯,但是完全值得.
Takes some getting used to, but totally worth it.
又读: