js模块化之自定义模块(页面模块化加载)
来源:互联网 发布:docker java api 编辑:程序博客网 时间:2024/04/27 22:21
#1 Passing parameter to method
Starting of slow, we let our require module return a JavaScript object with a method that accepts a parameter. This is pretty basic stuff, and should be sufficient for most scenarios.
index.html
<script src="scripts/require.js"></script><script> require(['scripts/app'], function(app){ app.greet('World'); });</script>
app.js
define(function(){ return { greet: function(name){ alert('Hello ' + name); } };});
#2 Passing object to method
While #1 works great when you have one, or only a handful of parameters, it can get quite messy when you're dealing with a lot of parameters. To counter this we can let our module accept an object instead.
index.html
<script src="scripts/require.js"></script><script> require(['scripts/app'], function(app){ app.greet({ salutation: 'Dr.', name: 'Who' }); });</script>
app.js
define(function(){ return { greet: function(config){ alert('Hello ' + config.salutation + ' ' + config.name); } };});
#3 Using RequireJS configuration
By loading the pre-defined RequireJS module aptly named "module" into your own module, you can define and access configuration data.
Note: The definition must be done before you include the require.js file, and this only works for define and not require modules.
index.html
<script> var require = { config: { 'app': { //This must match your module name name: 'Sherlock' } } };</script><script data-main="scripts/app" src="scripts/require.js"></script>
app.js
define(['module'], function(module){ alert('Hello ' + module.config().name);});
#4 Using a separate configuration module
Sometimes you'll have multiple modules needing the same input, then you can define a separate configuration module, and load it into your module like any other. I think this gives an nice clean separation between logic and data, but it can be a bit of an overkill i many situations.
index.html
<script> var require = { config: { 'config': { name: 'Everybody' } } };</script><script data-main="scripts/app" src="scripts/require.js"></script>
config.js
define(['module'], function(module){ return { name: module.config().name }});
app.js
require(['config'], function(config){ alert('Hello ' + config.name);});
- js模块化之自定义模块(页面模块化加载)
- js模块化加载(requirejs)
- 【 js 模块加载 】深入学习模块化加载(node.js 模块源码)
- js模块化之模块依赖处理
- javascript模块化加载sea.js
- js模块化之require.js
- js模块化之sea.js
- Dojo初探之1:AMD规范,编写符合AMD规范(异步模块加载机制)的模块化JS(其中dojo采用1.11.2版本)
- javascript模块化、模块加载器初探
- JS 模块化
- 模块化js
- js模块化
- js模块化
- js模块化
- JS模块化
- js模块化
- js 模块化
- js模块化
- 使用jquery的FormData上传文件
- NOIP2016 [愤怒的小鸟] 状压DP
- mysql的配置文件(调优之后)
- 制作地图d3.js
- jquery获取子元素
- js模块化之自定义模块(页面模块化加载)
- js 注册事件对象
- 时间递增循环执行脚本
- mysql清理日志
- flume
- jwt的详细说明
- CentOS 6.5/6.6 安装mysql 5.7
- 如何解决Visual Studio2015无法创建C++控制台应用程序,重复弹出新建项目窗口的问题
- ldap基本知识