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

       在默认的DOM事件中,如"click","mousedown","mouseover"等, 其所触发事件的回调中默认只会传入一个参数,即event对象本身

    button = document.getElementById('button1');
    button.addEventListener('click',function(){});// arguments[0] = event
    button.addEventListener('click',function(e){});// arguments[0] = event

    很多时候我们的回调函数可能不仅仅只有一个,而且会自定义一些特定事件实现观察者模式,那么如何自定义呢?

    首先定义Event,包含两个属性:on(绑定事件, 回调函数),emit(事件名)触发事件,另外还有一个静态属性即Event[eventName]表示所有绑定的事件

    let Event = {
        //通过on接口监听事件eventName
        //如果事件eventName被触发,则执行callback回调函数
        on:function(eventName, callback){
            this[eventName] = this[eventName] || [];
            this[eventName].push(callback);
        },
        //触发事件 eventName
        emit:function(eventName){
            let params = arguments.length > 1 ? Array.from(arguments).slice(1) : [];
            if (this[eventName]) {
                // 方法1
                Array.prototype.forEach.call(this[eventName],function(args) {
                    args.apply(this, params);
                });
                // 方法2
                for (let callback of this[eventName]) {
                    params.forEach(callback);
                }
                // 方法3
                this[eventName].forEach(function(callback) {
                    callback.apply(this, params);
                })
            }
        }
    };

    绑定test事件:

    Event.on('test',function(result){
        console.log(result);
    });
    Event.on('test',function(){
        console.log('test');
    });
    Event.emit('test','hello world'); 
    输出'hello world' 和 'test'
     
    创建其他对象
    var person1 = {};
    var person2 = {};

    使用Object.assign 将Event的属性赋值给person1,2

    Object.assign(person1, Event);
    Object.assign(person2, Event);

    然后person1,2各自绑定事件call1,call2

    person1.on('call1',function(){
        console.log('person1');
    });
    person2.on('call2',function(){
        console.log('person2');
    });

    最后测试事件:

    person1.emit('call1');  //输出'person1'
    person2.emit('call1');  //没有输出
    person1.emit('call2');  //没有输出
    person2.emit('call2');  //输出'person2'

    如果想要传递多个参数:

    let person3 = {};
    Object.assign(person3, Event);
    person3.on('call1',function(...args){
        console.log(args);
    });
    person3.emit('call1',1,2,3,4)
     
  • 相关阅读:
    自己改了个{svn服务器端绿色版}
    Android去掉顶部的阴影
    SqliteOpenHelper的onUpgrade()死活不运行的解法
    前端模拟发送数据/调试的好工具:Chrome下的PostmanREST Client
    mouseenter & mouseleave VS mouseover & mouseout
    Android WindowManager$BadTokenException异常应对案例
    Eclipse快捷键大全(转载)
    360桌面JSAPI一个诡异的bug:客户端与网页通过js通信
    《你在哪》1.34强势发布,新增“图片墙”
    经过一个月的奋斗,我的第一个Android作品《麦芒》诞生了
  • 原文地址:https://www.cnblogs.com/BigJ/p/js_event.html
Copyright © 2011-2022 走看看