在前面两篇文章中,分别叙述了通过html旧标签来做数据的绑定工作的好处与实现,通过整理,把绑定方法的代码包装成Jquery的plug型式。
下载地址:/Files/csnowfox/jquery.jq.databinding.rar
文件jquery.jq.databinding.js所有源码为:
/**//*
* jQuery databinding plugin
* Version 1.0 (06/14/2007)
* @requires jQuery v1.1.1
*
* Copyright (c) 2007 JingleQ
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
/**//**
* bind the datas to the dom node talbe which like
* <table border="0" cellspacing="5" cellpadding="5" id="ta">
* <tbody>
* <!-- 定制menu是为了使标题和下面的列表可以有不一样的样式布局 -->
* <tr id="menu">
* <td>用户名</td>
* <td>密码</td>
* </tr>
* <!-- 用于数据绑定 -->
* <tr id="def">
* <td bindingData="name" bindingPattern="[function] changeName({0})"></td>
* <td bindingData="password"></td>
* </tr>
* <!-- 下面是其它的布局辅助绑定数据后依然位于表格底部 -->
* <tr>
* <td colspan="2"> --- 分页 ---</td>
* </tr>
* </tbody>
* </table>
*
*
* itemCallBackFunction is a callback function
* using like this
*
* $("#ta").bindingItemsData(dataMap,function(l,it){
* $(it).hover(function(){
* $(it).addClass("blue");
* },function(){
* $(it).removeClass("blue");
* })
* });
*
* @example $("#ta").bindingItemsData(dataMap);
* @example with callback function $("#ta").bindingItemsData(dataMap,function(l,it) {});
* @name bindingItemsData
* @type jQuery
*/
jQuery.fn.bindingItemsData = function (datas, itemCallBackFunction) {
var self = this;
this.find("#def").each(function (i,n) {
for (index in datas) {
var newTr = $(n).clone();
// --- 标记列表 ---
newTr.attr("item","true");
newTr.find("td").each(function(k,o){
if (o.bindingPattern != undefined || o.bindingPattern == "") {
try {
o.bindingPattern = o.bindingPattern.replace("[function]","");
o.innerHTML = eval(o.bindingPattern.replace("\{0\}","'" + datas[index][o.bindingData] + "'"));
} catch (e) {
alert(e);
}
} else {
o.innerHTML = datas[index][o.bindingData];
}
})
self.find("#def").after(newTr);
}
})
// --- 通过回调添加列表样式 ---
if (itemCallBackFunction != undefined) {
$("#ta").find("tr[@item]").each(function(l,it) {
itemCallBackFunction(l,it)
}
);
}
return ta;
}
/**//**
* bind the data to the dom node which like
* <span id="dt"
* bindingData="name"
* bindingPattern="[function] changeName({0})">
* </span>
*
* @example $("span").bindingSpanData(dataMap);
* @name bindingSpanData
* @type jQuery
*/
jQuery.fn.bindingSpanData = function(data){
return this.each(function (i,n) {
if (n.bindingPattern != undefined || n.bindingPattern == "") {
try {
n.bindingPattern = n.bindingPattern.replace("[function]","");
n.innerHTML = eval(n.bindingPattern.replace("\{0\}","'" + data[n.bindingData] + "'"));
} catch (e) {
alert(e);
}
} else {
n.innerHTML = data[n.bindingData];
}
})
}