浅谈事件绑定与事件委托机制
事件绑定与事件委托机制
事件绑定顾名思义则是在元素标签上绑定相应的行为事件。事件委托也就是说,自身元素的行为事件交由其他父类元素去监管实现。具体js代码我们可以看下面代码实现,
来帮助初学者彻底了解什么是事件绑定与委托。
结构层(HTML)
<ul calss="parent">
<li class="child"></li>
<li class="child"></li>
<li class="child"></li>
<li class="child"></li>
</ul>
行为层(JavaScript 本文采用ES5标准编写)
(function(){
//简单的事件委托工具,未考虑IE6下的兼容性,仅供理解委托事物
window.EventUtil = {
hadelrs:{},
on:function(dom,dom1,event,fn){
//判断是否存在委托,不存在则创建一个dom1的委托事件函数池
if(this.hadelrs[dom1] ){
this.hadelrs[dom1] .push(fn);
if(this.hadelrs[dom1] ){
this.hadelrs[dom1] .push(fn);
} else {
this.hadelrs[dom1] = [fn];
}
this.hadelrs[dom1] = [fn];
}
//监听受委托的dom根据对应的事件触发对象,来触发dom1事件函数
document.querySelector(dom).addEventListener(event, function(evn){
//判断 事件触发是否来源于委托 元素dom1
if(evn.target == document.querySelector(dom1)) {
for(var i in EventUtil.hadelrs[dom1]){
try {
try {
EventUtil.hadelrs[dom1][i](event); //执行事件函数
} catch(err){
console.warn(err);
console.warn(err);
}
}
}
})
},
off: function(dom1,fn){
if(EventUtil.hadelrs[dom1]){
for(var i in EventUtil.hadelrs[dom1]){
if(EventUtil.hadelrs[dom1][i] == fn){
EventUtil.hadelrs[dom1].splice(i,1); //事件函数池移除事件
breack;
}
}
}
}
}}())
//调用实现
EventUtil.on('.parent','.parent li',click,function(e){console.log('----------li--------')})