javaScript设计模式——AMD模块化

Before

在学习AMD之前我们回顾一下RequireJs在javascript中的作用吧!!!

RequireJs

index.html

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="a.js"></script>
    </head>
    <body>
      <span>body</span>
    </body>
</html>

index.js

(function(){
    function fun1(){
      alert("it works");
    }

    fun1();
})()

用作用域块防止污染全局变量,但是运行结果却是alert执行的时候,html内容一片空白。
<span>body</span>并未被显示,当点击确定后,才出现,这就是JS阻塞浏览器渲染导致的结果。
那么我们就开始上RequireJs代码叭!!!

  • 准备工作:需要requierjs,到官网去下叭requirejs.org
  • requirejs定义了三个变量:define,require,requirejs,其中require === requirejs,一般使用require更简短
    将之前的index.js 写成 阻塞.js
define((function() {
    function fun1(){
        alert('ahahah');
    }
    fun1();
}))
  • 先来个简单的叭
    在html中引入:
require(["阻塞"], function(){
            alert('load finished');
        });

第一个参数是一个数组,数组的每一项是对应的define的js路径名,
第二个参数是一个callback function,用来处理加载完毕后的逻辑。

  • 来个男的——加载文件
require.config({
            paths: {
                "jquery": ["http://libs.baidu.com/jquery/2.0.3/jquery"],
                "a": ["阻塞"]
            }
        });
        require(["require", "a"], function($,_) {
           console.log($);//require.js
           alert('load finish')
           $(["a"],function(){
               alert('again load finish');
           });
        })

require.config使用来配置模块加载位置,可以加载多个模块,并给其起一个小名。
在require中只需要写进去小名就可。

  • 完整的html代码:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://requirejs.org/docs/release/2.3.6/minified/require.js"></script>
    <script>
        // require(["阻塞"], function(){
        //     alert('load finished');
        // });

        require.config({
            paths: {
                "jquery": ["http://libs.baidu.com/jquery/2.0.3/jquery"],
                "a": ["阻塞"]
            }
        });
        require(["require", "a"], function($,_) {
           console.log($);//require.js
           alert('load finish')
           $(["a"],function(){
               alert('again load finish');
           });
        })
    </script>
    <title>Document</title>
</head>

<body>
    <span>body</span>
</body>

</html>

开始AMD的表演

Asynchronous Module Definition (AMD) 异步模块定义
阮一峰大师的理解:它采用异步方式加载模块,模块的加载不影响它后面语句的运行。所有依赖这个模块的语句,都定义在一个回调函数中,等到加载完成之后,这个回调函数才会运行。
requirejs官网中的AMD

特点

  • 异步调用
  • 高扩展性
  • 实现了解耦

define and require

define 定义模块

define(
    module_id /*可选的*/,
    [dependencies] /*可选的*/,
    definition function /*用来实例化模块或者对象的方法*/
);
  • 当module_id参数不存在时,成这个模块为匿名模块。
  • 当匿名模块时,模块认定的概念是DRY(don’t repeat yourself)的,即。因为这样一来代码方便切换,你可以很容易地把它移动到其它地方(或者文件系统的其他位置),而不需要更改代码内容或者它的模块ID。
  • dependencies参数代表了我们正在定义的模块需要的dependency数组。
  • 第三个参数(“definition function” or “factory function”) 是用来执行的初始化模块的方法。

直接上栗子
三个js文件,其中一个主js myModule.js文件写define,其他两个js通过myModule.js一起导出
myModule.js

define("myModule",
    ["foo", "bar"],
    function(foo, bar){
        var myModule = {
            doFoo: function() {
                console.log('dofoo');
            },
            doBar: function() {
                console.log('doBar')
            }

        };

        return myModule;
       
    });

foo.js

console.log('i am a foo')

bar.js

console.log('i am a bar')

来解剖一下代码吧!!!
上面已经说过啦!!

  • define第一个参数为id
  • 第二个参数为数组,数组每一项是dependency,大白话一点,就是景来需要公共的功能依赖。
  • 第三个就是callback function,加载完了依赖后需要做什么,都写在这了,可以在函数中先定义对象再返回,也可以直接返回。
    直接返回看这个:
define("myModule",
    ["foo", "bar"],
    function(foo, bar){
        
       return {
            doFoo: function() {
                console.log('dofoo');
            },
            doBar: function() {
                console.log('doBar')
            }

        };
    });

注意的地方是:
define中的Module_id数组中的每一项 都 和require中的参数尽量保持一致

require 处理依赖加载

首先看require第一个参数是difine中的依赖数组

 require(["foo","bar"], function( foo, bar){
            console.log('load finished');
            foo.doFoo(); //doFoo() undefined
            // bar.doBar();
        })

在看看require第一个参数是define路径名

  require(["myModule"], function( myModule ){
            console.log('load finished');
            myModule.doFoo();//dofoo
            myModule.doBar(); //dobar

        })

看一眼运行结果:
在这里插入图片描述
再看一个栗子:
foo.js

define(['foo'],function(foo){
    return {
        add: function(x, y){
            console.log(x + y);
        }
    }
})

myModule.html

require(['foo'], function(foo){
           foo.add(1,2)
       })

最终结果为 3

如果有多个类似于foo.js这样的小依赖,我们可以向上一个栗子那样,定义多个放在一个主要的define中,通过return foo.add() 在 reqeire中第一个参数分别传他们小依赖的名,来使用。
foo.js

define(['foo'],function(foo){
    return {
        add: function(x, y){
            console.log(x + y);
        }
    }
})

bar.js

define(['bar'],function(x,y){
    return {
        reduce: function(x, y){
            console.log(x - y);
        }
    }
});

myModule.js

define(['foo', 'bar'],function(foo, bar){
    return {
        add: function(x,y){
            foo.add(x,y)
        },
        reduce: function(x,y){
            bar.reduce(x, y)
        }
    }
});

myModule.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://requirejs.org/docs/release/2.3.6/minified/require.js"></script>
    <title>Document</title>
    <script>

       require(['foo','bar'], function(foo,bar){
           foo.add(1,2);//3
           bar.reduce(1,2)//-1
       })
    
    </script>
</head>
<body>
    
</body>
</html>

推荐阅读

嘻嘻嘻~~有几篇是我写的有几篇我局的不错的别人写de
ES6 Modelus
AMD
AMD , CMD, CommonJS,ES Module,UMD比较
javascript 设计模式 AMD CommonJS
requirejs.org
CommenJS

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值