1. 程式人生 > >require.js 入門講解(二)

require.js 入門講解(二)

require.js使用AMD體系,採用非同步方式載入模組,即模組的載入不影響,載入程式碼後面語句的執行,採用回撥函式方式在模組載入完畢後執行回撥函式,語法如下示意:

require([module], callback);

該語法說明如下:

module代表需要載入的模組,多個模組採用陣列方式表示,依次載入,實際載入的程式碼如下示意:

  1. require(['math','Eng'], function (math) {

  2.     math.add(2, 3);

  3. Eng.say('hello');

  4.   });

採用require.js語法更適合瀏覽器的執行環境,因為模組程式碼來自遠端伺服器,受網路執行環境影響,程式碼的下載即載入速度都可能比較緩慢,因此需要AMD方式,非同步的進行程式碼的載入與執行;

node.js的模組載入程式碼:var math = require('math');採用CommonJS的方式,適合在伺服器端環境執行,在瀏覽器環境中可能導致模組載入的卡頓。因此在瀏覽器環境中採用var math = require('math')載入模組是錯誤的方式;

二、採用require.js載入模組

       理論上,require.js載入的模組,必須是按照AMD規範、用define()函式定義的模組。但是實際上,雖然已經有一部分流行的函式庫(比如jQuery)符合AMD規範,更多的庫並不符合。那麼,require.js是否能夠載入非規範的模組呢?

回答是可以的。

這樣的模組在用require()載入之前,要先用require.config()方法,定義它們的一些特徵。

舉例來說,underscore和backbone這兩個庫,都沒有采用AMD規範編寫。如果要載入它們的話,必須先定義它們的特徵。

非AMD模組載入語法示例:

  1. require.config({

  2.     shim: {

  3.       'underscore':{

  4.         exports: '_'

  5.       },

  6.       'backbone': {

  7.         deps: ['underscore', 'jquery'],

  8.         exports: 'Backbone'

  9.       }

  10.     }

  11.   });

實際開發環境中,require載入示例:

  1. //=====================模組載入配置======================

  2. requirejs.config({

  3. baseUrl: '/Scripts',

  4. paths: {

  5. app: '/Scripts/app',

  6. jquery: '/Scripts/jquery-1.10.2.min',

  7. 'jquery.ui': '/Scripts/jquery-ui.min',

  8. 'jquery.validate.min': '/Scripts/jquery.validate.min',

  9. 'jsGrid': '/Scripts/jsgrid.min'

  10. },

  11. shim: {

  12. 'jsGrid': {

  13. deps: ['jquery']

  14. },

  15. 'jquery.validate.min': {

  16. deps: ['jquery']

  17. }

  18. }

  19. });

  20. //==========================載入主模組====================

  21. requirejs(['app/main']);

模組定義示例:

  1. //======================定義應用層面的模組=====================

  2. define(["jquery", "jquery.ui", "jsGrid", 'jquery.validate.min'], function ($,ju,jsGrid,jv) {

  3. var formSubmitHandler = $.noop;

  4. var datas = { "name": "test", "password": "test" };

  5. var editItem = { Name: '', Age: '', Address: '', Country: '', Married: '' };

  6. var oprResult = false;

  7. var showDetailsDialog = function (dialogType, client) {

  8. $("#name").val(client.Name);

  9. $("#age").val(client.Age);

  10. $("#address").val(client.Address);

  11. $("#country").val(client.Country);

  12. $("#married").prop("checked", client.Married);

  13. $("#detailsDialog").dialog("option", "classes.ui-dialog", "highlight");

  14. buttons = [{

  15. text: "Ok",

  16. icon: 'ui-icon-mail-open',

  17. type: "submit",

  18. value:"submit",

  19. click: function () {

  20. //$(this).dialog("close");

  21. oprResult = true;

  22. //$("form").validate().form();

  23. if ($("#detailsForm").valid())

  24. {

  25. values = { Name: $("#name").val(), Age: $("#age").val(), Address: $("#address").val(), Country: $("#country").val(), Married: $("#married").prop("checked") };

  26. editItem = $.extend(editItem, values);

  27. submitData(editItem);

  28. }

  29. }

  30. }];

  31. var dl = $("#detailsDialog").dialog("option", "buttons", buttons);

  32. dl.dialog("open");

  33. };

  34. var submitData = function (e) {

  35. var i = $.Deferred();

  36. updateData = { Name: e.Name, Age: e.Age, Country: e.Country, Address: e.Address, Married: e.Married };

  37. $.ajax({

  38. url: '/Grid/UpdateData',

  39. type: 'put',

  40. dataType: 'json',

  41. contentType: 'application/json; charset=utf-8',

  42. data: JSON.stringify(updateData)

  43. }

  44. ).done(function (e) {

  45. alert('update data successed');

  46. i.resolve(e);

  47. $("#detailsDialog").dialog("close");

  48. }).fail(function (e) {

  49. alert('update failed!');

  50. });

  51. return i.promise();

  52. };

  53. var saveClient = function (client, isNew) {

  54. $.extend(client, {

  55. Name: $("#name").val(),

  56. Age: parseInt($("#age").val(), 10),

  57. Address: $("#address").val(),

  58. Country: parseInt($("#country").val(), 10),

  59. Married: $("#married").is(":checked")

  60. });

  61. $("#jsGrid").jsGrid(isNew ? "insertItem" : "updateItem", client);

  62. $("#detailsDialog").dialog("close");

  63. };

  64. var loadData = function (e) {

  65. var d = $.Deferred();

  66. //=================服務端分頁需要將頁面索引傳遞到服務端=======================

  67. pageSize = e.pageSize;

  68. pageIndex = e.pageIndex;

  69. $.ajax({

  70. url: '/Grid/IndexData',

  71. type: 'post',

  72. dataType: 'json',

  73. contentType: 'application/json; charset=utf-8',

  74. data: JSON.stringify(datas)

  75. }

  76. ).done(function (e) {

  77. alert('load data successed');

  78. //===========================服務端分頁的話就沒必要取子集了=========================

  79. subdata = e.slice(pageSize * (pageIndex - 1), pageSize * pageIndex);

  80. pagingdata = { data: subdata, itemsCount: e.length };

  81. d.resolve(pagingdata);

  82. }).fail(function (e) {

  83. alert('load failed!');

  84. });

  85. return d.promise();

  86. };

  87. var insertData = function (e) {

  88. var d = $.Deferred();

  89. $.ajax({

  90. url: '/Grid/UpdateData',

  91. type: 'put',

  92. dataType: 'json',

  93. contentType: 'application/json; charset=utf-8',

  94. data: JSON.stringify(e)

  95. }

  96. ).done(function (data) {

  97. alert('load data successed');

  98. d.resolve(data);

  99. }).fail(function (msg) {

  100. alert('load failed:' + msg + "!");

  101. });

  102. return d.promise();

  103. };

  104. var deleteData = function (e) {

  105. var d = $.Deferred();

  106. $.ajax({

  107. url: '/Grid/DeleteData',

  108. type: 'delete',

  109. dataType: 'json',

  110. contentType: 'application/json; charset=utf-8',

  111. data: JSON.stringify(e)

  112. }

  113. ).done(function (data) {

  114. alert('delete data successed');

  115. d.resolve(data);

  116. }).fail(function (msg) {

  117. alert('delete failed:' + msg + "!");

  118. });

  119. return d.promise();

  120. }

  121. return {

  122. showDetailsDialog,

  123. saveClient,

  124. loadData,

  125. submitData,

  126. insertData,

  127. deleteData

  128. }

  129. });