//声明主题对象
var Subject = function(name) {
this.name = name
this.register = []
}
Subject.prototype = {
//注册观察者
submit(observe) {
this.register.push(observe)
console.log('观察者' + observe.id + '定阅了本主题')
return this
},
//观察者取关
unsubmit(observe) {
var that = this
this.register.map(function(name, index) {
if (name == observe) {
that.register.splice(index, 1)
console.log(name.id + '取关了本主题')
}
})
return this
},
//在某些特定的时刻,由主题向一切的定阅者宣布事宜
radioOn(name, value) {
this.register.map(rg => {
rg[name](value)
})
return this
}
}
var Observe = function(id) {
this.id = id
}
//供主题挪用的事宜
Observe.prototype = {
updata(msg) {
console.log('观察者' + this.id + '更新了信息,信息为' + msg)
},
init() {
console.log('观察者' + this.id + '进行了初始化')
},
play(type) {
console.log('观察者' + this.id + '最先玩起了' + type)
}
}
//实例化一个主题
var subject1 = new Subject('PUBG')
//实例化三个观察者对象
var observe1 = new Observe('张三')
var observe2 = new Observe('李四')
var observe3 = new Observe('赵六')
subject1.submit(observe1)
.submit(observe2)
.radioOn('init')
.radioOn('updata', '天命圈hhh')
.unsubmit(observe1)
.submit(observe3)
.radioOn('play', subject1.name)
/* 观察者张三定阅了本主题
* 观察者李四定阅了本主题
* 观察者张三进行了初始化
* 观察者李四进行了初始化
* 观察者张三更新了信息,信息为天命圈hhh
* 观察者李四更新了信息,信息为天命圈hhh
* 张三取关了本主题
* 观察者赵六定阅了本主题
* 观察者李四最先玩起了PUBG
* 观察者赵六最先玩起了PUBG
*/
js的观察者形式
原文作者:Bismarck
原文地址: https://segmentfault.com/a/1190000018143740
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://segmentfault.com/a/1190000018143740
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。