2

前几天一哥们,去面试遇到到一个用原生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
2k 声望161 粉丝

很多事情不是因为有希望才去坚持,而是坚持了才有希望。