美文网首页
自定义事件js

自定义事件js

作者: 贫下码农 | 来源:发表于2018-07-19 19:47 被阅读0次

    title: 自定义事件
    date: 2017-06-06 15:36:04
    tags: 自定义事件


    js的自定义事件

    code

    
    function EventTarget() {
        this.handlers = {};
    }
    
    EventTarget.prototype = {
        constructor: EventTarget,
        addHandler: function(type, handler) {
            if (typeof this.handlers[type] == 'undefined') {
                this.handlers[type] = [];
            }
            this.handlers[type].push(handler);
        },
        fire: function(type, event) {
            if (!event.target) {
                event.target = this;
            }
            if (this.handlers[type] instanceof Array) {
                var handlers = this.handlers[type];
                for (var i = 0, len = handlers.length; i < len; i++) {
                    handlers[i](event);
                }
            }
        },
        remove: function(type, handler) {
            if (this.handlers[type] instanceof Array) {
                var handlers = this.handlers[type];
                for (var i = 0, len = handlers.length; i < len; i++) {
                    if (handlers[i] === handler) {
                        break;
                    }
                }
                handlers.splice(i, 1);
            }
        }
    };
    
    

    usage

    var target = new EventTarget();
    //事件处理函数
    function fn(event){
      console.log(event);
    }
    //注册事件
    target.addHandler('testEvent', fn);
    //触发事件
    target.fire('testEvent', {name : 'Cloud'});//第二个参数是传递的内容,可自定义
    

    用处

    • 可以用于界面间的传值
    • 创建松耦合的代码

    相关文章

      网友评论

          本文标题:自定义事件js

          本文链接:https://www.haomeiwen.com/subject/ushxmftx.html