扫码关注官方订阅号
首先事件是 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
不行拉,addEventListener是DOM元素的方法,想要自己在对象上用,就等于要自己实现一个观察者模式。如果使用jQuery,可以利用jQuery的Callback api快速实现。如果想要实现对属性变化的监听,可以看一下Object.defineProperty.
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
首先事件是 Element 对象才有的方法。
如果其他对象要使用事件,只好自己实现一个了。其实就是观察者模式或叫发布-订阅模式。
不行拉,addEventListener是DOM元素的方法,想要自己在对象上用,就等于要自己实现一个观察者模式。如果使用jQuery,可以利用jQuery的Callback api快速实现。如果想要实现对属性变化的监听,可以看一下
Object.defineProperty.