[函数]jquery下组织javascript代码(js函数化)
从神奇的"$"函数开始"$"函数将在文档加载完成之后为一个指定的button 绑定事件,这些代码在单个网页中工作正常。但是如果我们还有其它的网页,我们将不得不重复这个过程。
代码如下:
Say Hello
//when dom ready, do something.
//bind click event to a button.
$(function(){
$('#sayHello').click(function(){
alert('Hello world!');
});
});
如果我们需要另一个行为的button怎么办?比如象这样:
代码如下:
Unlike it
//when dom ready, do something.
//bind click event to a button.
$(function(){
$('#sayUnlike').click(function(){
alert('I unlike it.');
});
});
接下来,更多的问题出现了,我们需要很多这样的button, 这好象也不难。
代码如下:
Unlike it
//Change to a class selector to match all the button elements.
$(function(){
$('.sayUnlike').click(function(){
alert('I unlike it.');
});
});
一个页面里面同种出现了两种button ......
代码如下:
Say Hello
Unlike it
$(function(){
$('.sayHello').click(function(){
alert('Hello world!');
});
$('.sayUnlike').click(function(){
alert('I unlike it.');
});
});
但是呢,不是所有的页面都会用到这两种的button,为了不在页面上使用额外的选择器,我们要作一些必要的调整,因为基于class的选择器的性能相对于id选择器开销很大,需要遍历所有dom元素,并使用正则表达式匹配class属性来选定满足条件的元素。
代码如下:
if($page == 'A'){?>
$(function(){
$('.sayHello').click(function(){
alert('Hello world!');
});
});
} ?>
if($page == 'B'){?>
$(function(){
$('.sayUnlike').click(function(){
alert('I unlike it.');
});
});
} ?>
我们的项目功能越来越复杂,经过一段时间以后,变成了这个样子, quick but dirty......
代码如下:
if($page == 'A' or $page == "C" and $page is not "D"){ ?>
......
} ?>
if($page == "B" or $page == "E" and $page is not "X"){ ?>
.....
} ?>
if($page == "B" or $page == "E" or $page == "C"){ ?>
.....
} ?>
这真是太糟糕了,我们需要在一个页面上加载许多个代码片断才能绑定所有的事件,如果我们再将不同的代码分装入多个js文件中这将增加多个页面资源的http请求,不论是管理还是用户体验都将面临挑战,我们需要找到一个更佳的解决方案。
既然 class selector 的开销这么大,我们能不能在一次扫描中绑定所有的事件?我们可以尝试一下:
代码如下:
//Register global name space.
var Yottaa = Yottaa || {};
Yottaa.EventMonitor = function(){
this.listeners = {};
}
//Bind all event.
Yottaa.EventMonitor.prototype.subscribe=function(msg, callback){
var lst = this.listeners[msg];
if (lst) {
lst.push(callback);
} else {
this.listeners[msg] = [callback];
}
}
// Create the event monitor instance.
var event_monitor = new Yottaa.EventMonitor();
function load_event_monitor(root){
var re = /a_(\w+)/; //using a regular expression to filter all event object.
var fns = {};
$(".j", root).each(function(i) {
var m = re.exec(this.className);
if (m) {
var f = fns[m[1]];
if (!f) { //如果事件处理函数不存在则创建函数对象.
f = eval("Yottaa.init_"+m[1]);
fns[m[1]] = f;//调用绑定函数.
}
f && f(this);
}
});
}
$(function(){
// when dom ready, bind all event.
load_event_monitor(document);
});
//Here is 2 sample components.
(责任编辑:admin)