最近做前台设计的MM,应用了layui.js框架,是一个可以按模块加载的js框架,可以实现UI上的一些效果,比如"手风琴折叠"面板。我看了下源码,抽出了其框架,应用到公司的项目中,代码示例如下:
/** search.page-v1.0.0 by wbq/*/
!function (w) {
"use strict";
var c = {
showMessageElement: "#tipMessage",
waitElement: "#mainload",
},
o = function () { this.v = "1.0.0";
this.PostData = {};
this.KeywordList = [];
this.filterUrl = "";
this.listurl = ""; }; o.prototype.buildPostData = function () {
var that = this;
$('[nf-value]').each(function (index, item) {
if (item.type === "checkbox") {
that.PostData[item.id] = item.checked;
}
else if (item.type === "radio") {
if (item.checked) {
that.PostData[item.name] = item.value;
}
} else {
if (item.id)
that.PostData[item.id] = item.value;
}
});
return that.PostData;
},
o.prototype.config = function (e) {
e = e || {};
for (var t in e) c[t] = e[t];
return this;
},
o.prototype.post = function (url, postData, callback) {
if (!postData) {
postData = this.buildPostData();
}
var that = this;
$.ajax({
url: url,
type: "POST",
data: postData,
cache: false,
beforeSend: function (XMLHttpRequest) {
if (c.waitElement)
$(c.waitElement).show();
},
success: function (result) {
if (callback != null && typeof callback == 'function')
callback(result);
},
complete: function () {
if (c.waitElement)
$(c.waitElement).hide();
},
error: function (xhr, status, exp) { that.ShowMessage(exp);
}
});
},
o.prototype.get = function (postData, uri, callback) {
var that = this;
$.ajax({
url: uri,
type: "get",
cache: false,
data: postData,
success: function (result) {
if (callback != null && typeof callback == 'function')
callback(result);
},
error: function (xhr, status, exp) { that.ShowMessage(exp);
}
});
}, o.prototype.CheckAll = function () {
$("input[name='ckImport']").each(function (i) {
if ($(this).prop("checked")) {
$(this).prop("checked", false);
}
else {
$(this).prop("checked", true);
}
});
},
o.prototype.Search = function (keyword) { };
w.pageRequest = new o; w.chooseLetter = function (obj) { };
w.chooseKeyword = function (obj) { }; }(window);
此js结构比较简单明了,核心原理:通过立即执行函数,为window对象定义了一个属性pageRequest,它指向名为o的function实例,接下来,我们的注意力就集中到了o的上面。var o=function(){}这是函数表达式的写法。在函数内部,定义了一些属性。然后在o.prototype,即函数的原型上面定义了一组方法,它们在所有的实例上可以共享。我们还可以在window对象上定义其它方法。比如chooseLetter和chooseKeyword。