原生js,编写一个自定义的事宜监听

头几天一哥们,去口试遇到到一个用原生js 编写的事宜监听,

原题是这模样滴!

function EventDispatcher()
{
}
 
/**
 * @param {string} eventStr
 * @param {Function} callBack
 * */
EventDispatcher.prototype.addEventListener = function(eventStr, callBack)
{
};
 
/**
 * @param {string} event
 * @param {*=} body
 * */
EventDispatcher.prototype.dispatchEvent = function(event, body)
{
};
 
var d = new EventDispatcher();
function callback(e) {
console.log(‘callback fired’);
console.log(‘Event body: ’+e.body);
}
d.addEventListener(‘testEvent’, callback);
d.dispatchEvent(‘testEvent’, ‘testMessage’);

//expexted console output:
//callback fired
//Event body: testMessage

---------------分割线------------------

然后~~~就兴高采烈的去看一下,大神的能够直接疏忽,

就愿望帮到一小部分的人~~就很高兴啦!

简朴道理就是往addEventListener 内里的type挂载一个函数,然后在dispatchEvent内里挪用这个函数,这么一说是否是以为很简朴???

好 直接上代码!!!

function EventDispatcher() {
    this.events = {};
}
            
EventDispatcher.prototype.addEventListener = function(type, handler) {
    if (typeof handler != 'function') return;
    this.events[type] = handler;
};
            
EventDispatcher.prototype.dispatchEvent = function(type, body) {
    var e = {};
    e.body = body;
    this.events[type](e);
};
            
var d = new EventDispatcher();
            
d.addEventListener('testEvent', function(e){
    console.log('callback fired-----' + e.body);
});
            
d.dispatchEvent('testEvent', '213123123');

终了 收工(总以为有点像定阅宣布的意义2333)~~

很无耻的凑字数~~~很无耻的凑字数~~~很无耻的凑字数~~~很无耻的凑字数~~~很无耻的凑字数~~~很无耻的凑字数~~~很无耻的凑字数~~~很无耻的凑字数~~~

    原文作者:naice
    原文地址: https://segmentfault.com/a/1190000005718369
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞