在园子里有很多关于jQuery插件的文章,尤其 以下2篇文章:
这2位大神基础讲的很清楚,在这里就不多说了,主要那个小需求来练练:
需求说明:一个标题插件,可以通过后端取数,自定义标题,自定义样式
讨论:插件通常不都是加载一下就不操作了,比如表格插件,加载数据,刷新等等。
今天练习的控件就简单给大家理理写控件的思路,(有问题,有意见大家指出。)
; (function ($) {
$.fn.cyTitle = function (options) {
//一些操作
return new cyTitle(options);
}
function cyTitle(Options) {
//这里定义插件属性
$.extend(this, Options);
this.init(Options);
}
cyTitle.prototype = {
init: function () {
//这里构建插件内容
}
}
})(jQuery)
每个插件都应该包含以上部分,这个就不多说了(上面2为大神的文章说的很清楚),从实际编写出发。 (demo)
点击加载控件列出标题(未定义标题),点击刷新更改标题(ajax取数)。
下面一步步看代码:
(本来请求txt的结果发现博客园不能上传和请求,放着runjs上也只能是js文件了。。。)
<div style="border: 1px dotted #888; width: 300px; height: 100px;">
<input type="button" class="cyTitleCore" title="load" value="加载控件" />
<input type="button" class="cyTitleCore" title="ref" value="刷新" />
<div id="div1cyTitle"></div>
</div>
<script type="text/javascript">
$(function () {
$(".cyTitleCore").click(function () {
core[$(this).attr("title")]();
})
var core = {
load: function () {
this.list = $("#div1cyTitle").cyTitle({
background: "#888"
});
},
ref: function () {
//这里直接调用插件的ref方法来刷新取数
if (this.list) {
this.list.ondatabind = function (that, e) {
e.url = "Service.js"; //指定取数的url
e.params = { //指定取数的参数
"id": (+new Date())
};
}
this.list.ref();
}
}
}
})
</script>
上面是加载控件和刷新的调用;
首先点击加载按钮可以看到是调用了插件cyTitle,并且指定背景色。先不看刷新,来看看插件到底怎么写的!
$.fn.cyTitle = function (options) {
options = options || {};
var domEl = this.get(0); //获得绑定元素的dom对象
if (!domEl) throw "未找到绑定元素!";
if (domEl["cyTitle"]) { //这里如果调用元素的dom对象上有这个控件就直接返回 (避免了在同一个元素上多次调用出BUG)
return domEl["cyTitle"];
}
options.el = domEl; //这里在构建插件的时候直接用this.el就能访问元素的dom对象
return new cyTitle(options);
}
function cyTitle(Options) {
//这里定义插件属性
$.extend(this, Options);
this.ajaxType = "get";
this.el.cyTitle = this; //把控件放着dom元素的cyTitle属性上
this.ondatabind = null; //ajax取数的绑定方法
this.init(Options);
}
cyTitle.prototype = {
init: function () {
this.load(); //加载控件
},
load: function () {
$(this.el).append("<h1>" + (this.text || "未知") + "</h1>"); //如果指定了Options.text就显示指定的内容
this.ref(); //调用ajax取数(类似与表格插件第一次加载)
},
ref: function () {
this.bgCss();
var e = {
url: null
};
this.doEvt("ondatabind", e); //这里调用前面定义的取数方法的内容(url, params)
//依次类推我们可以写绑定前(在绑定方法前面调用),绑定后(执行异步后调用) 等等
if (e.url) {
var my = this;
$[this.ajaxType](e.url, e.params, function (res) {
if (res) {
$(my.el).find("h1").text(res);
}
},‘html‘);
}
},
doEvt: function (name, p) {
if (this[name]) {
this[name](this, p);
}
return this;
},
bgCss: function () {
$(this.el).css("background", this.background);
}
};
以上就是整个插件的内容,
优点:
用一个demo练习编写插件,才知道其中的乐趣,先说到这里。谢谢
实在忙,最近搞了个girhub.io博客写了个滚动条插件。有兴趣的可以看看内涵demo
原文:http://www.cnblogs.com/Leo_wl/p/5115172.html