原生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('属性发生了变化');
使用自定义事件,可以很容易实现面向对象的编程方式,并且在对象的状态发生改变时,重新进行模板的渲染。