原生js实现自定义事件

原生js实现自定义事件


用JavaScript的话来说,观察者模式的实质就是你可以对程序中某个对象的状态进行观察,并且在其发生改变时能够得到通知。

利用观察者模式可以很容易的实现自定义事件,具体代码如下:

var Event=function() {
  this.subscibers={};//保存事件的回调函数  
};
Event.prototype={
    constructor:Event,//保持原型链的完整
    on:function(type,callback) {  //绑定事件
        this.subscibers[type]=[];
        this.subscibers[type].push(callback);
      } else {
        this.subscibers[type].push(callback);
      }
    },
    off:function(type) {  //移除事件
      this.subscibers[type]=[];
    },
    emit:function(type) { //触发事件
      var t=this;
      if(typeof this.subscibers[type]=='object') {
        this.subscibers[type].forEach(function(fn,i) {
          fn.call(t);
        });
      } 
    }
};

var s=new Event();
s.title='测试自定义事件';

s.on('change.title',function() {
  console.log(this.title);
});

s.setTitle=function(value) {
  this.title=value;
  this.emit('change.title')
};

s.setTitle('属性发生了变化');

使用自定义事件,可以很容易实现面向对象的编程方式,并且在对象的状态发生改变时,重新进行模板的渲染。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值