javascript - js里普通的对象不能再自己新建的对象上绑定虚拟事件吗?

查看:140
本文介绍了javascript - js里普通的对象不能再自己新建的对象上绑定虚拟事件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

//创建一个window对象上的事件监听,监听hello事件
window.addEventListener('hello', function(e){
    console.log(e);
}, false);

//创建一个Event实例,事件名:hello
var e  = new Event('hello');
//在window对象上触发这个事件
window.dispatchEvent(e);

我自己新建个对象可以吗?就像下面的代码:

var apple = {};
apple.addEventListener('hello', function(e){
    console.log(e);
}, false);

//创建一个Event实例,事件名:hello
var e  = new Event('hello');

apple.dispatchEvent(e);

解决方案

首先事件是 Element 对象才有的方法。

console.log(Element.prototype.addEventListener)  // true
console.log(Object.prototype.addEventListener)   // undefind

如果其他对象要使用事件,只好自己实现一个了。其实就是观察者模式或叫发布-订阅模式

Object.prototype.eventCache = {};
Object.prototype.addEvent = function(eventName, fn){
    this.eventCache[eventName] = this.eventCache[eventName] || [];
  this.eventCache[eventName].push(fn);
}
Object.prototype.dispatch = function(){
  var _this = this;
    var eventName = [].shift.call(arguments, 1);
    var args = arguments;
  this.eventCache[eventName].forEach(function(f){
    f.apply(_this, args);
  });
}

var obj = {};
obj.addEvent('hello', function(){
    console.log('hello')
});
obj.addEvent('hello', function(str){
    console.log('hello ' + str)
});
obj.dispatch('hello', 'world');

// 最后输出
// hello
// hello world

这篇关于javascript - js里普通的对象不能再自己新建的对象上绑定虚拟事件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆