码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript自定义事件

时间:2019-01-06 18:24:25      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:需要   name   class   编码   javascrip   handle   使用   and   标题   

标题JavaScript自定义事件

最近遇到一个基于jQuery项目,项目中的功能节点页面都是通过iframe实现,但是各个iframe之间有时需要相互通信,互相相应一些事件,为了更愉快的编码所以想到了自定义事件,还别说用起来竟然有点像vue的组件通信


top.events = {
    on: function (name, func) {
      if(!this.handles){
        this.handles = {};
      }
      if(!this.handles[name]){
        this.handles[name] = '';
      }
      else this.handles[name] = func;
    },
    emit: function (name) {
      if(this.handles[name]){
        //arguments是伪数组所以通过call来使用slice
        this.handles[name].apply(null, Array.prototype.slice.call(arguments, 1));
      }
    },
    destory: function (name) {
      if(this.handles && this.handles[name]) delete this.handles[name];
    }
  };

//绑定
top.events.on('test', function() {});

//触发
top.events.emit('test', param));

//销毁
top.events.destory('test');

来源:https://segmentfault.com/a/1190000017497498

JavaScript自定义事件

标签:需要   name   class   编码   javascrip   handle   使用   and   标题   

原文地址:https://www.cnblogs.com/lalalagq/p/10229209.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!