javascript - js里普通的对象不能再自己新建的对象上绑定虚拟事件吗?
巴扎黑
巴扎黑 2017-04-11 10:53:44
[JavaScript讨论组]
巴扎黑
巴扎黑

全部回复(2)
大家讲道理

首先事件是 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
PHPz

不行拉,addEventListener是DOM元素的方法,想要自己在对象上用,就等于要自己实现一个观察者模式。如果使用jQuery,可以利用jQuery的Callback api快速实现。如果想要实现对属性变化的监听,可以看一下
Object.defineProperty.

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号