AMD规范实例

rand.js

1 define(function () {
2     //关于抽奖 中奖的概率实现
3     function rand(m, n) {
4         return Math.ceil(Math.random() * (n - m + 1)) + m - 1;
5     }
6     //暴露数据
7     return rand;
8 })

peercent.js

 1 define(["rand"], function (rand) {
 2     //封装一个概率函数
 3     function percent(num) {
 4         //获取 1-100 的随机值
 5         let n = rand(1, 100);
 6         //判断
 7         if (n <= num) {
 8             return true;
 9         } else {
10             return false;
11         }
12     }
13     //暴露数据
14     return percent;
15 })

 

main.js

requirejs.config({
    //模块标识名与模块路径映射
    paths: {
        //不需要加文件后缀
        "loger": "modules/loger",
        "dataService": "modules/dataService",
        "jquery": "libs/jquery-1.10.1",
        "rand": "modules/rand",
        "percent": "modules/percent"
    }
})

//引入使用模块
// requirejs(['loger'], function (loger) {
//     loger.showMsg()
// });

requirejs(['percent','jquery'], function(percent, $) {
    //绑定事件
    $('button').click(function(){
        let result = percent(80);
        //判断
        if(result){
            console.log("我们中奖啦, 自由啦!! 远方啦!! 诗在哪儿呢!!")
        }else{
            console.log("再接再厉, 继续努力, 埋头苦干, 也要抬头看看!!");
        }
    });
})

 

index.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <title>Document</title>
 7 </head>
 8 <body>
 9     
10     <button>点击抽奖</button>
11 
12     <script data-main="js/main.js" src="js/libs/require.js"></script>
13 </body>
14 </html>

 

posted @ 2020-06-16 11:44  全情海洋  阅读(249)  评论(0编辑  收藏  举报