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)

 

 
posted @ 2018-03-01 10:57  KeepLearning_!  阅读(239)  评论(0编辑  收藏  举报