用RequireJS編寫JavaScript模組

來源:互聯網
上載者:User

模組化編寫JavaScript,在web前端程式不斷擴大的時候,是一個很好的重構技術。

下面的例子有兩個模組,

artDialog模組依賴jquery和jquery.artDialog庫,提供了彈出錯誤對話方塊的功能。

require.config({paths: {"jquery": "../thirdParty/jquery-1.8.0.min","jquery.artDialog": "../../plugin/artDialog4.1.6/jquery.artDialog"}});define("artDialog",       ["jquery", "jquery.artDialog"],       function ($, artDialog) {       return {       cancelText: "",       language: "",       // language should be either 'cn' or 'en'       init: function (language) {       this.language = language;       if (language === "cn") {       this.cancelText = "取消";       } else {       this.cancelText = "Cancel";       }       },       error: function (message) {       $.dialog({       icon: "error",       content: message,       cancelVal: this.cancelText,       ok: function () {       this.close();       }       });       }       };       }      );

解釋一下:

1.require.config裡面的paths 用了key: value形式,key是名稱簡寫,path是從當前位置找到依賴檔案的路徑

2.define是定義模組的意思,第一個參數"artDialog"是指這個模組的名稱,數組裡面是本模組依賴的其他js模組,

3.RequireJS看到2定義的相依模組後,會去載入這些js檔案,載入完成後,會調用函數function($, artDialog)

4.回呼函數反回一個json對象,裡面有成員變數和函數。

ajaxUtility模組內部使用了artDialog模組,看看代碼:

require.config({paths: {"jquery": "../thirdParty/jquery-1.8.0.min","artDialog": "./dialog"}});define("ajaxUtility",       ["jquery","artDialog"],       function ($, artDialog) {       return {       cancelText: "",       language: "",       // language should be either 'cn' or 'en'       init: function (language) {       this.language = language;       artDialog.init(language);       if (this.language === "cn") {       this.cancelText = "取消";       } else {       this.cancelText = "Cancel";       }       },       // popup an error dialog       defualtErrorHandler: function (jqXHR, textStatus) {       artDialog.error("Ajax request got an error:" + textStatus);       },       // execute .ajax function and except the returned data type is json       // handler(msg) will be callback when .ajax succeeded       // errorHandler(jqXHR, textStatus) willl be callback if .ajax failed       exe: function (urlPath, asyncWay, method, dataValue, handler, errorHandler, context) {       var error, request;       if (errorHandler) {       error = errorHandler;              } else {       error = this.defaultErrorHandler;       }       request = $.ajax({       url: urlPath,       async: asyncWay,       type: method,       dataType: 'json',       data: dataValue       });       // request.done(handler);       request.done(       (function (ob, hdl) {       return function(msg) {       hdl(ob, msg);         }       })(context, handler)       );       request.fail(error);       },       // post data to server using .ajax       // handler(msg) will be callback when .ajax succeeded       // errorHandler(jqXHR, textStatus) willl be callback if .ajax failed       post: function (urlPath, asyncWay, dataValue, handler, errorHandler, context) {       this.exe(urlPath, asyncWay, 'POST', dataValue, handler, errorHandler, context);       },       // call web method with GET to server using .ajax       // handler(msg) will be callback when .ajax succeeded       // errorHandler(jqXHR, textStatus) willl be callback if .ajax failed       get: function (urlPath, asyncWay, dataValue, handler, errorHandler, context) {       this.exe(urlPath, asyncWay, 'GET', dataValue, handler, errorHandler, context);       }       };       }      );

1.require.config裡面說明了模組artDialog在dialog.js檔案中

2.define語句定義了ajaxUtility模組,並且在載入dialog.js檔案和jquery完成後,調用函數function($, artDialog) ,注意,此時參數artDialog就是前面一個模組返回出來的對象。

依賴載入的說明,chrome調試發現,不用擔心共同依賴的jquery會被載入兩次,RequireJS很智能。也不用擔心依賴順序,只要每個模組都正確定義了自己的相依模組,順序就會有保障。

最後給一個第三個模組示範如何依賴這兩個模組,以及其他模組:

require.config({paths: {"ajaxUtility": "./ajax_utility","jquery.validate": "../../plugin/jquery-validation-1.9.0/jquery.validate.min","flexigrid": "../../plugin/flexigrid-1.1/js/flexigrid","flexigrid.pack": "../../plugin/flexigrid-1.1/js/flexigrid.pack","jquery.ui": "../../plugin/jquery-ui-1.8.23.custom/js/jquery-ui-1.8.23.custom.min"}});require(["ajaxUtility"], function(ajaxUtility) {ajaxUtility.init("cn");require(["jquery.validate", "flexigrid", "flexigrid.pack", "language", "jquery.ui"], function(util) {require(["log"], function(util) {$(document).ready(function() {log.init();})});});});

最外層的require載入的是ajaxUtility,因此它最先被載入,juery, jquery.artDialog和dialog.js都會被載入,然後其他依賴比如jquery.ui就無須擔心jquery是否載入。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.