require.js 入門講解(二)
require.js使用AMD體系,採用非同步方式載入模組,即模組的載入不影響,載入程式碼後面語句的執行,採用回撥函式方式在模組載入完畢後執行回撥函式,語法如下示意:
require([module], callback);
該語法說明如下:
module代表需要載入的模組,多個模組採用陣列方式表示,依次載入,實際載入的程式碼如下示意:
-
require(['math','Eng'], function (math) {
-
math.add(2, 3);
-
Eng.say('hello');
-
});
採用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模組載入語法示例:
-
require.config({
-
shim: {
-
'underscore':{
-
exports: '_'
-
},
-
'backbone': {
-
deps: ['underscore', 'jquery'],
-
exports: 'Backbone'
-
}
-
}
-
});
實際開發環境中,require載入示例:
-
//=====================模組載入配置======================
-
requirejs.config({
-
baseUrl: '/Scripts',
-
paths: {
-
app: '/Scripts/app',
-
jquery: '/Scripts/jquery-1.10.2.min',
-
'jquery.ui': '/Scripts/jquery-ui.min',
-
'jquery.validate.min': '/Scripts/jquery.validate.min',
-
'jsGrid': '/Scripts/jsgrid.min'
-
},
-
shim: {
-
'jsGrid': {
-
deps: ['jquery']
-
},
-
'jquery.validate.min': {
-
deps: ['jquery']
-
}
-
}
-
});
-
//==========================載入主模組====================
-
requirejs(['app/main']);
模組定義示例:
-
//======================定義應用層面的模組=====================
-
define(["jquery", "jquery.ui", "jsGrid", 'jquery.validate.min'], function ($,ju,jsGrid,jv) {
-
var formSubmitHandler = $.noop;
-
var datas = { "name": "test", "password": "test" };
-
var editItem = { Name: '', Age: '', Address: '', Country: '', Married: '' };
-
var oprResult = false;
-
var showDetailsDialog = function (dialogType, client) {
-
$("#name").val(client.Name);
-
$("#age").val(client.Age);
-
$("#address").val(client.Address);
-
$("#country").val(client.Country);
-
$("#married").prop("checked", client.Married);
-
$("#detailsDialog").dialog("option", "classes.ui-dialog", "highlight");
-
buttons = [{
-
text: "Ok",
-
icon: 'ui-icon-mail-open',
-
type: "submit",
-
value:"submit",
-
click: function () {
-
//$(this).dialog("close");
-
oprResult = true;
-
//$("form").validate().form();
-
if ($("#detailsForm").valid())
-
{
-
values = { Name: $("#name").val(), Age: $("#age").val(), Address: $("#address").val(), Country: $("#country").val(), Married: $("#married").prop("checked") };
-
editItem = $.extend(editItem, values);
-
submitData(editItem);
-
}
-
}
-
}];
-
var dl = $("#detailsDialog").dialog("option", "buttons", buttons);
-
dl.dialog("open");
-
};
-
var submitData = function (e) {
-
var i = $.Deferred();
-
updateData = { Name: e.Name, Age: e.Age, Country: e.Country, Address: e.Address, Married: e.Married };
-
$.ajax({
-
url: '/Grid/UpdateData',
-
type: 'put',
-
dataType: 'json',
-
contentType: 'application/json; charset=utf-8',
-
data: JSON.stringify(updateData)
-
}
-
).done(function (e) {
-
alert('update data successed');
-
i.resolve(e);
-
$("#detailsDialog").dialog("close");
-
}).fail(function (e) {
-
alert('update failed!');
-
});
-
return i.promise();
-
};
-
var saveClient = function (client, isNew) {
-
$.extend(client, {
-
Name: $("#name").val(),
-
Age: parseInt($("#age").val(), 10),
-
Address: $("#address").val(),
-
Country: parseInt($("#country").val(), 10),
-
Married: $("#married").is(":checked")
-
});
-
$("#jsGrid").jsGrid(isNew ? "insertItem" : "updateItem", client);
-
$("#detailsDialog").dialog("close");
-
};
-
var loadData = function (e) {
-
var d = $.Deferred();
-
//=================服務端分頁需要將頁面索引傳遞到服務端=======================
-
pageSize = e.pageSize;
-
pageIndex = e.pageIndex;
-
$.ajax({
-
url: '/Grid/IndexData',
-
type: 'post',
-
dataType: 'json',
-
contentType: 'application/json; charset=utf-8',
-
data: JSON.stringify(datas)
-
}
-
).done(function (e) {
-
alert('load data successed');
-
//===========================服務端分頁的話就沒必要取子集了=========================
-
subdata = e.slice(pageSize * (pageIndex - 1), pageSize * pageIndex);
-
pagingdata = { data: subdata, itemsCount: e.length };
-
d.resolve(pagingdata);
-
}).fail(function (e) {
-
alert('load failed!');
-
});
-
return d.promise();
-
};
-
var insertData = function (e) {
-
var d = $.Deferred();
-
$.ajax({
-
url: '/Grid/UpdateData',
-
type: 'put',
-
dataType: 'json',
-
contentType: 'application/json; charset=utf-8',
-
data: JSON.stringify(e)
-
}
-
).done(function (data) {
-
alert('load data successed');
-
d.resolve(data);
-
}).fail(function (msg) {
-
alert('load failed:' + msg + "!");
-
});
-
return d.promise();
-
};
-
var deleteData = function (e) {
-
var d = $.Deferred();
-
$.ajax({
-
url: '/Grid/DeleteData',
-
type: 'delete',
-
dataType: 'json',
-
contentType: 'application/json; charset=utf-8',
-
data: JSON.stringify(e)
-
}
-
).done(function (data) {
-
alert('delete data successed');
-
d.resolve(data);
-
}).fail(function (msg) {
-
alert('delete failed:' + msg + "!");
-
});
-
return d.promise();
-
}
-
return {
-
showDetailsDialog,
-
saveClient,
-
loadData,
-
submitData,
-
insertData,
-
deleteData
-
}
-
});