标签:gossip Oday char 工厂 观察者 read typeof TE doctype
最近在看《JavaScript面向对象编程指南》种的设计模式,主要有三种,工厂模式,装饰器模式和观察者模式,今天分享一下关于观察者模式的演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>订阅发布模式</title>
</head>
<body>
<script>
// 定义发布者对象
var publisher = {
subscribers: [],
//添加订阅者
addSubscriber: function(callback) {
this.subscribers[this.subscribers.length] = callback
},
//删除订阅者
removeSubscriber: function(callback) {
for(var i=0; i<this.subscribers.length; i++) {
if(tis.subscribers[i] === callback) {
delete(this.subscribers[i])
}
}
},
//发布事件
publish: function(what) {
for(var i=0; i<this.subscribers.length; i++) {
if(typeof this.subscribers[i] === ‘function‘) {
this.subscribers[i](what)
}
}
},
//将对象转变车发布者
make: function(o) {
for(var i in this) {
o[i] = this[i];
o.subscribers = []
}
}
}
// 订阅者,负责当发生某个事件的时候调用publish事件
var blogger = {
writeBlogPost: function() {
var context = ‘today is‘ + new Date();
this.publish(context)
}
}
var la_times = {
newIssue: function() {
var paper = ‘Martians have loaded on Earth!‘;
this.publish(paper)
}
}
// 它们都很容易装变为发行商
publisher.make(blogger)
publisher.make(la_times)
// 准备两个简单对象
var jack = {
read: function(what) {
console.log(‘I just read that‘ + what)
}
};
var jill = {
gossip: function(what) {
console.log(‘You don\‘t hear it from me, but ‘ + what)
}
}
// 他们可以订阅blogger对象,只需要提供事件发生时的回调函数
blogger.addSubscriber(jack.read);
blogger.addSubscriber(jill.gossip);
blogger.writeBlogPost()
</script>
</body>
</html>
标签:gossip Oday char 工厂 观察者 read typeof TE doctype
原文地址:https://www.cnblogs.com/shenwh/p/9186607.html