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

    function test(){
      this.list = {}
    };
    test.prototype = {
      constructor:test,
      add:function(key,fn){
        if(typeof this.list[key] == 'undefined'){//检测hello是否存在
          this.list[key] = [];
        }
        this.list[key].push(fn);//将hello加入事件数组
      },
      triggle:function(){
        var key = Array.prototype.shift.call(arguments);//arguments为伪数组
        var fns = this.list[key];//存在多个hello事件?
        if(!fns || fns.length<=0)return;
        for(var i=fns.length-1;i>=0;i--){
          fns[i].apply(this,arguments);//依次执行所有的hello
        }
      }
    }

    var one = new test();
    one.add('hello',function(tmp){
      console.log(tmp)
    })
    one.triggle('hello','world')
    one.triggle('hello','mdzz')
    one.add('say',function(tmp){
      console.log(tmp)
    })
    one.triggle('say','hi')
    var two = new test();
    two.add('biubiubiu',function(tmp){
      console.log(tmp)
    })
    two.triggle('biubiubiu','boomboomboom!');

    可以参考红皮书和JavaScript设计模式与开发实践

  • 相关阅读:
    减治算法之寻找第K小元素问题
    OpenGL的版本号历史和发展
    动态注冊监听
    Thinking in Java -- 类型信息RTTI
    Unity3D
    Oracle改动字段类型
    函数定义
    foreach
    数组
    结构体
  • 原文地址:https://www.cnblogs.com/92xcd/p/9831192.html
Copyright © 2011-2022 走看看