zoukankan      html  css  js  c++  java
  • 自定义事件

    1.自定义事件,其实就是事件的监听,触发,是设计模式中的观察者模式。主要有三个方法:on,off,emit。

    基本实现如下:

    Array.prototype.remove = function(item){
    var temp = [];
    var index;
    for(var i=0; i<this.length;i++)
    {

    if(this[i]==item)
    {
    index = i;
    break;
    }
    }
    if(typeof index!="undefined")
    this.splice(index,1);
    return this;
    }

    function MyEvent()
    {
    this.listener=[];
    }
    MyEvent.prototype = {
    on:function(type,fn){

    if(this.listener[type]&&Object.prototype.toString.call(this.listener[type])=="[object Array]")
    {
    this.listener[type].push(fn);
    }
    else
    {
    this.listener[type]=[];
    this.listener[type].push(fn);
    }
    },
    off:function(type,fn)
    {
    if(this.listener[type]&&Object.prototype.toString.call(this.listener[type])=="[object Array]")
    {
    if(Object.prototype.toString.call(fn)=="[object Function]")
    {
    this.listener[type].remove(fn);
    }
    else
    {
    this.listener[type]=[];
    }
    }
    },
    emit:function(type){
    if(this.listener[type]&&Object.prototype.toString.call(this.listener[type])=="[object Array]")
    {
    for(let i of this.listener[type])
    {
    i();
    }
    }
    }
    }

    var myEvent = new MyEvent();
    myEvent.on("click", clickFn);
    myEvent.emit("click");
    myEvent.off("click", clickFn);
    myEvent.emit("click");
    function clickFn()
    {
    console.log("clickFn");
    }

    注意jquery的事件中的 回调函数中传的event 与真实的event有区别会丢失真实event的一些属性,比如 pageshow 事件,使用 jquery绑定的不会有e.persisted 属性,所以不能用jquery绑定该事件

  • 相关阅读:
    凸优化之基追踪
    [转]广义正交匹配追踪(gOMP)
    SAMP论文学习
    sublime学习笔记
    IEEE Trans 2009 Stagewise Weak Gradient Pursuits论文学习
    [转]压缩感知重构算法之分段正交匹配追踪(StOMP)
    IEEE Trans 2008 Gradient Pursuits论文学习
    Git学习笔记
    树状数组【bzoj1103】: [POI2007]大都市meg
    模拟赛 10-25上午考试记
  • 原文地址:https://www.cnblogs.com/chillaxyw/p/9357669.html
Copyright © 2011-2022 走看看