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绑定该事件

  • 相关阅读:
    git和TortoiseGit安装
    poi导出excel
    POI生成word文档
    java反编译工具
    如何把wecenter的推荐的问题模块单独调取出来?
    想学网站运营?我教你啊!(下)
    想学网站运营?我教你啊!(中)
    想学网站运营?我教你啊!(上)
    织梦模块管理里面空白
    Discuz/X3.1去掉标题中的Powered by Discuz!以及解决首页标题后的"-"
  • 原文地址:https://www.cnblogs.com/chillaxyw/p/9357669.html
Copyright © 2011-2022 走看看