观察者模式1
by 苹果熊
JavaScript
var publisher = {
subscribers: {
any: []
},
subscribe: function(fn, type) {
type = type || 'any'
if(!this.subscribers[type]) {
this.subscribers[type] = []
}
this.subscribers[type].push(fn)
},
unsubscribe: function(fn, type) {
type = type || 'any'
var subs = this.subscribers[type]
for(var i = 0; i < subs.length; i++) {
subs.splice(i, 1)
}
},
publish: function(cont, type) {
type = type || 'any'
var subs = this.subscribers[type]
for(var i = 0; i < subs.length; i++) {
subs[i](cont)
}
}
}
function makePublisher(o) {
for(var i in publisher) {
if(publisher.hasOwnProperty(i) && typeof publisher[i] === 'function') {
o[i] = publisher[i]
}
}
o.subscribers = {
any: []
}
}
//do something
var teacher = {
task: function(tasks) {
this.publish(tasks)
}
}
makePublisher(teacher)
var student = {
homeWork: function(tasks) {
console.log(tasks)
}
}
teacher.subscribe(student.homeWork)
teacher.task('完成100篇论语抄写!')
teacher.task('完成100篇将进酒抄写!')