JS模块化编程-requirejs

amd_and_require.jpg

先来看看下面的代码吧:

……
    <script type='text/javascript' src='<%=contextPath%>/dwr/engine.js'> </script>
    <script type='text/javascript' src='<%=contextPath%>/dwr/util.js'> </script>
    <script type='text/javascript'
        src='<%=contextPath%>/dwr/interface/IvmPlanAdjustDwrService.js'> </script>
    <script language="JavaScript" src="<%=contextPath%>/application/include/common.js"></script>
    <script  src="<%=contextPath%>/application/include/jquery-1.3.2.js"></script>
    <script type="text/javascript" src="<%=contextPath%>/application/include/floatdiv/js/jquery.nyroModal-1.6.2.pack.js"></script>
    <script  src="<%=contextPath%>/application/include/dhtmlx/grid/dhtmlxcommon.js"></script>
    <script  src="<%=contextPath%>/application/include/dhtmlx/grid/dhtmlxgrid.js"></script>
    <script  src="<%=contextPath%>/application/include/dhtmlx/grid/dhtmlxgridcell.js"></script>
    <script  src="<%=contextPath%>/application/include/dhtmlx/grid/ext/dhtmlxgrid_splt.js"></script>
    <script  src="<%=contextPath%>/application/include/dhtmlx/grid/ext/dhtmlxgrid_hmenu.js"></script>
    <script  src="<%=contextPath%>/application/include/dhtmlx/grid/ext/dhtmlxdataprocessor.js"></script>
    <script  src="<%=contextPath%>/application/include/dhtmlx/grid/ext/dhtmlxgrid_undo.js"></script>
<script type="text/javascript">

function exit(){
 if(!myDataProcessor.getSyncState()){
    if(confirm("本页还有数据未保存!需要保存吗?")){
        myDataProcessor.sendData();
    }else{
        return true;
    }
 }
}

function showDiffer(){
    //var rowId = mygrid.getRowId(i);
    var ippUuidCellId=mygrid.getColIndexById('ippUuid');
    var ippUuid=mygrid.cells(mygrid.getSelectedId(),ippUuidCellId).getValue();
    //alert(ippUuid);
    $('#projectCompareForm.nyroModal').nyroModal({bgColor: '#CCCCCC',minHeight:'160',closeButton:'<a href="#" class="nyroModalClose" id="closeBut" title="关闭">关闭</a>'});
    $("#projectCompareForm").attr("action","<%=request.getContextPath()%>/servlet/IvmPlanAdjustApproveServlet?operate=queryAdjustDetail&ippUuid="+ippUuid);
    $("#projectCompareForm").submit();
    //$("#projectCompare").load("<%=request.getContextPath()%>/servlet/IvmPlanAdjustApproveServlet?operate=queryAdjustDetail&ippUuid="+ippUuid);
    //$("#projectCompare").css("top","200px");
    //$("#projectCompare").css("left","100px");
    //window.open("<%=request.getContextPath()%>/servlet/IvmPlanAdjustApproveServlet?operate=queryAdjustDetail&ippUuid="+ippUuid, '_blank', 'toolbar=no,menubar=no,location=no,resizable=no,scrollbars=yes,status=yes,menubar=no,height=300,width=1200,top=10,left=50');
}
……

这代码是我本人两三年前和一个同事(目前在阿里)共同完成的,上面的代码只是在同一个jsp页面上所有js代码的一小部分,整个jsp文件1000行以上,80%是js,如果这个系统现在还在运行,有人需要重新升级一下系统的话,这肯定是一大悲剧!!引用如此多的JS库,那么多js代码,注释还相当的少,有谁能看懂?

接下来就告诉大家如何来解决这个问题吧,这里要介绍的工具requirejs即将闪亮登场,在介绍它之前你必须先了解一下:

AMD: The Asynchronous Module Definition (AMD) API specifies a mechanism for defining modules such that the module and its dependencies can be asynchronously loaded. This is particularly well suited for the browser environment where synchronous loading of modules incurs performance, usability, debugging, and cross-domain access problems.

AMD:异步模块定义规范(AMD)制定了定义模块的规则,这样模块和模块的依赖可以被异步加载。这和浏览器的异步加载模块的环境刚好适应(浏览器同步加载模块会导致性能、可用性、调试和跨域访问等问题)。

为什么把英文和中文都写出来呢? 因为我个人觉得有的时候硬要把一此IT的专用术语翻译成中文来理解有点费劲

它是一群牛B人们定义的规范,具体的内容自己去看吧:
https://github.com/amdjs/amdjs-api/blob/master/AMD.md

我们今天要用的requirejs就是实现了这个规范的一个js库。官方是这么定义requirejs的:

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

我是这样理解的:requirejs就是一个加载js文件和模块的小工具。使用Requirejs可以改善js代码的质量和性能,就是用来解决您在一开始看到的那堆“扯蛋”的代码,哈哈

直入正题吧,我将借用官方的get start带您入门,入门后就只能自己修炼了。

先来看看代码结构

.
├── app
│   ├── main.js
│   └── messages.js
├── app.js
├── index.html
└── lib
    ├── print.js
    └── require.js

app目录下面是我们的程序代码,lib目录下是我们要用的requirejs和会引用到的一些第三方库,来看看代码吧:

index.html

<!DOCTYPE html>
<html>
    <head>
        <script data-main="app" src="lib/require.js"></script>
    </head>
    <body>
        <h1>Hello World</h1>
    </body>
</html>

简单吧,只需要一行js,先加载requirejs,指定data-main,也就是和其它语言中的main方法一样,相当于程序的一个入口。

app.js

// For any third party dependencies, like jQuery, place them in the lib folder.

// Configure loading modules from the lib directory,
// except for 'app' ones, which are in a sibling
// directory.
requirejs.config({
    baseUrl: 'lib',
    paths: {
        app: '../app'
    }
});

// Start loading the main app file. Put all of
// your application logic in there.
requirejs(['app/main']);

很简单,对requirejs进行配置,指定模样加载路径等信息,然后直接加载main.js,来看看main.js里有什么:

define(function (require) {
    // Load any app-specific modules
    // with a relative require call,
    // like:
    var messages = require('./messages');

    // Load library/vendor modules using
    // full IDs, like:
    var print = require('print');

    print(messages.getHello());
});

这里引用了一个自己写的messages模块和一个第三文的print模块,调用相关的方法将相应的信息加印出来。

messages.js 里就是根据AMD的规范定义了一个方法:

define(function () {
    return {
        getHello: function () {
            return 'Hello World';
        }
    };
});

print.js 也是一样的,这里只是项目目录组织形式上把第三方实现的都放到lib目录下。

define(function () {
    return function print(msg) {
        console.log(msg);
    };
});

怎么样?还可以理解吧? 最终效果就是在控制台打出“Hello World”。

OK,本文到此就结束了,只是带你入门(或者说只是告诉你有个叫requirejs的东东),其它的全靠你自己了,因为搜索引擎上一搜“requirejs”,会出来很多很多的好教程,我不想再写一个,没什么意义。但是我还是建议您从官网开始你的模块化js编程之旅:http://requirejs.org


国际范程序必读:
程序员的编辑器-VIM(爱就是爱)
向开源社区贡献您的代码
在github上写博客
DevOps是什么东东?
js依赖管理工具bower

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容