简单事件追加案例

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<input type="button" id="btn" value="click"/>
<script>
    var btn = document.getElementById('btn');
    
   var event =  (function(){
        /*定义存储事件处理函数的对象,根据不同的事件名,将事件处理函数存储在对应的数组中*/
       var events = {
           'click':[],
           'load':[]
       }
       /*事件处理函数*/
       function on(node,type){
           /*dom元素+ on+ 事件名= 事件处理函数*/
           node['on'+type] = function (e) {
               /*遍历数组 events[type]*/
               for(var i = 0;i < events[type].length;i++){
                   /*上下文调用events[type][i]函数 返回自定义this  即Dom元素*/
                   events[type][i].apply(node,[e]);
               }
           };
       }
       /*调用*/
       on(window,'load');
       on(btn,'click');

       return {
           /*追加事件函数*/
           appEvent: function (node,type,fn) {
               /*判断事件名追加到对应的数组中*/
               if(type == 'click'){
                   events[type].push(fn);
               }else if(type == 'load'){
                   events[type].push(fn);
               }
               return this;
           },
           removeEvent: function (node,type,fn) {
               /*更加事件名遍历数组,在对应的数组中移除事件*/
               for(var i = 0;i < events[type].length;i++){
                   if(events[type][i] === fn){
                       break;
                   }
               }
               if(i != events[type].length){
                   events[type].splice(i,1);
               }
               return this;
           }
       }
   })();/*自调用*/
    var o = event;

    o.appEvent(btn,'click', function () {
        alert(123)
    });
    var f = function () {
        alert('454545');
    }
    o.appEvent(btn,'click',f).removeEvent(btn,'click',f);

</script>
</body>
</html>

 

posted on 2016-08-09 00:58  LCFLY  阅读(146)  评论(0编辑  收藏  举报

导航