在Github上看到一個js的外掛程式,於是興起自己也來嘗試坐下...於是參考GIthub上的一個項目自己也做個簡單的實驗。
可以先參考別人項目的組織及結構來開發代碼Github上看到的js外掛程式的代碼格式一般是這樣的:
(function(){ var MyApp = {}; //模組名 /* * 模組其他成員 */ //如 var Component = {} ; (function(){Component.xxx = function(){// do something } }); MyApp.Component = Component ; // 使用CommonJs模組類型 if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = MyApp; } exports.MyApp = MyApp;} //AMD模組if (typeof define === 'function' && define.amd) { define('MyApp', [], function () { return MyApp; });}//瀏覽器if (typeof window === 'object' && typeof window.document === 'object') { window.MyApp = MyApp;}})();這裡的 (function(){})匿名閉包是讓一切成為可能的基礎,而這也是JavaScript最好的特性,我們來建立一個最簡單的閉包函數,函數內部的代碼一直存在於閉包內,在整個運行周期內,該閉包都保證了內部的代碼處於私人狀態。
function () {
// ... 所有的變數和function都在這裡聲明,並且範圍也只能在這個匿名閉包裡
// ...但是這裡的代碼依然可以訪問外部全域的對象
}());
(function () {/* 內部代碼 */})(); //參考部落格深入理解javascript(http://www.cnblogs.com/TomXu/archive/2011/12/30/2288372.html)部落格或者
Javascript patterns書中內容
然後再要使用的地方調用該javascript檔案,調用方法也比較簡單如 : var myapp = MyApp ; com1 = myapp.Component. com1.xxx
下面用一個簡單的建立表格建立一個hello項目:
table.js
(function(){var hello = {};var table = {};(function(){table.init = function(){var element = document.body;var table = document.createElement('table');table.id = 'someId';table.border = '2';element.appendChild(table);var table = document.getElementById('someId');var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell1 = row.insertCell(0); cell1.innerHTML = '使用者名稱'; var cell2 = row.insertCell(1); cell2.innerHTML = '密碼'; };table.append = function(user_list){var table = document.getElementById('someId');console.info(user_list);for(var i=0 ,max = user_list.length; i< max ; i++){var rowCount = table.rows.length;console.info(user_list[i]);var row = table.insertRow(rowCount);var cell1 = row.insertCell(0);cell1.innerHTML = user_list[i].name; var cell2 = row.insertCell(1);cell2.innerHTML = user_list[i].age; }};})();hello.table = table;if (typeof window === 'object' && typeof window.document === 'object') { window.hello = hello;}})();測試頁面:
開發js控制項<script type="text/javascript" src="table.js"></script><script type="text/javascript">var table = hello.table;table.init();var users = [];for (var i=0;i<10;i++ ){var data = {};data['name'] = 'user'+i;data['age'] = i ;users.push(data);}table.append(users);</script>:
是不是很簡單....這樣當有這樣的需求的時候,就可以把自己喜歡做的東西開發成為這樣的js外掛程式了。。而且具有很好的可移植性.