观察者模式: 当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。
es5方式,兼容IE9+
<script>
var Event = (function () {
function _classCheck(instance, constructor) {
if (!(instance instanceof constructor)) {
throw new Error('Class constructor Child cannot be invoked without new')
}
}
function Event() {
this.events = {};
_classCheck(this,Event)
}
Event.prototype.on = function(name,fn) {
if(!this.events.hasOwnProperty(name)){
this.events[name] = []
}
this.events[name].push(fn)
};
Event.prototype.off = function(name,fn) {
if(!this.events.hasOwnProperty(name)){
console.error('该对象中找不到'+name+'方法')
return
}
this.events[name] = this.events[name].filter(function(item){
return item != fn
})
if(this.events[name].length == 0){
delete this.events[name]
}
};
Event.prototype.dispatch = function(name){
if(!this.events.hasOwnProperty(name)){
console.error('该对象中找不到'+name+'方法')
return
}
this.events[name].forEach(function(item,index){
item.call(this)
})
}
return Event;
})();
var ee = new Event();
function funC(){
console.log('hi')
}
ee.on('say',funC);
// ee.on('say',function(){
// console.log('hello')
// })
// ee.on('say',function(){
// console.log('hello2')
// })
ee.dispatch('say');
ee.off('say',funC)
ee.dispatch('say');
</script>
es6方式
<script>
class Event {
events = {}
on(name,fn){
if(!this.events.hasOwnProperty(name)){
this.events[name] = []
}
this.events[name].push(fn)
}
off(name,fn){
if(!this.events.hasOwnProperty(name)){
console.error('该对象中找不到'+name+'方法')
return
}
this.events[name] = this.events[name].filter(item=>{
return item != fn
})
if(this.events[name].length == 0){
delete this.events[name]
}
}
dispatch(name){
if(!this.events.hasOwnProperty(name)){
console.error('该对象中找不到'+name+'方法')
return
}
this.events[name].forEach(item=>{
item.call(this)
})
}
}
let ee = new Event();
function funC(){
console.log('hi')
}
ee.on('say',funC);
// ee.on('say',function(){
// console.log('hello')
// })
// ee.on('say',function(){
// console.log('hello2')
// })
ee.dispatch('say');
ee.off('say',funC)
ee.dispatch('say');
</script>