js学习笔记 - JavaScript的事件代理

[size=large]
[color=red]更新[/color]
http://docs.jquery.com/Release:jQuery_1.3
1.3支持原生支持了
不是我不明白
是世界变化太快
上午刚学到的技巧
晚上已经发现过时

....

Live Events

jQuery now supports "live events" - events that can be bound to all current - and future - elements. Using event delegation, and a seamless jQuery-style API, the result is both easy to use and very fast.


学习来源
http://www.yeeyan.com/articles/view/33485/24593
http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery

用途
"""
想象一下现在我们有一个10列、100行的HTML表格,你希望在用户点击表格中的某一单元格的时候做点什么。比如说我有一次就需要让表格中的每一个单元格在被点击的时候变成可编辑状态。如果把事件处理器加到这1000个单元格会产生一个很大的性能问题,并且有可能导致内存泄露甚至是浏览器的崩溃。相反地,使用事件代理的话,你只需要把一个事件处理器添加到table元素上就可以了,这个函数可以把点击事件给截下来,并且判断出是哪个单元格被点击了。

...

* 那些需要创建的以及驻留在内存中的事件处理器少了。这是很重要的一点,这样我们就提高了性能,并降低了崩溃的风险。
* 在DOM更新后无须重新绑定事件处理器了。如果你的页面是动态生成的,比如说通过Ajax,你不再需要在元素被载入或者卸载的时候来添加或者删除事件处理器了。

潜在的问题也许并不那么明显,但是一旦你注意到这些问题,你就可以轻松地避免它们:

* 你的事件管理代码有成为性能瓶颈的风险,所以尽量使它能够短小精悍。

我注:因为所以子元素的该事件都要过这里,所以先做判断是不是符合条件,再运算

* 不是所有的事件都能冒泡的。blur、focus、load和unload不能像其它事件一样冒泡。事实上blur和focus可以用事件捕获而非事件冒泡的方法获得(在IE之外的其它浏览器中),不过我们改天再说这个吧。
* 在管理鼠标事件的时候有些需要注意的地方。如果你的代码处理mousemove事件的话你遇上性能瓶颈的风险可就大了,因为mousemove事件触发非常频繁。而mouseout则因为其怪异的表现而变得很难用事件代理来管理。

"""

配合jquery的用法
1.原始用法

$('#thing').click(function(e) {
var target = $(e.target);

if (target.hasClass('quit') return doQuitStuff();
if (target.hasClass('edit') return doEditStuff();
// and so on...
});

2.便捷方式
a.定义

jQuery.fn.delegate = function(eventType, rules) {
return this.bind(eventType, function(e) {
var target = $(e.target);
for(var selector in rules)
if(target.is(selector))
return rules[selector].apply(this, arguments)
})
}

b.
使用

$("#thing").delegate("click", {
".quit": function() { /* do quit stuff */ },
".edit": function() { /* do edit stuff */ }
})
当然
"""
I’m not sure of the performance implications of using is() so heavily but some form of caching could be added if it was a problem. Still, it’s a really nice little bit of syntactic sugar that’s going into Low Pro for jQuery and I’ll be using it a lot.
"""[/size]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值