在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;
}
})();
测试页面:
<!doctype>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>开发js控件</title>
</head>
<body>
<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>
</body>
</html>
效果图:
是不是很简单....这样当有这样的需求的时候,就可以把自己喜欢做的东西开发成为这样的js插件了。。而且具有很好的可移植性.