1.未绑定dom对象的观察者模式demo
var scope = {
on:function(name,callback){
this.arr = this.arr || [];
this.arr[name] = {
callback: callback
}
},
trigger:function(name){
if(this.arr[name])this.arr[name].callback();
}
};
scope.on('hello',function(){
console.log('hello');
});
scope.trigger('hello');
实现比较简单。这样的实现方式有一个缺点就是不同的用户来定义的事件都存放在一个数组里,可能会产生覆盖,用户之间的事件没有隔离。不实用呀。
1.绑定dom对象的观察者模式demo
var scope = {
on:function(dom,name,callback){
this.arr = this.arr || [];
this.arr[dom] = this. arr[dom] || [];
this.arr[dom].push({
name:name,
callback:callback
})
},
trigger:function(dom,name){
if(this.arr[dom]){
var len = this.arr[dom].length;
for(var i = 0;i < len;i++){
if(this.arr[dom][i].name == name){
this.arr[dom][i].callback();
}
}
}
}
};
scope.on('id','he',function(){
console.log('id he');
})
scope.on('id','hu',function(){
console.log('id hu');
})
scope.trigger('id','he');
scope.trigger('id','hu');
scope.trigger('ss','he');//什么也不输出因为没有注册这个事件
这是jquery的自定义事件的实现原理。jquery还把各个模块之间的交互也通过事件订阅和触发的方式来相互通知,交互。有非常不错的隔离性,和模块化气质。