我不久之前就遇到了适合我的新模式-JS语言的观察者。因此,在Junior lvl上,我清楚地了解了它的工作原理,但不幸的是,我无法弄清楚如何向一个全球商店订阅两个不同的订户?
这是我下面的小例子:
class EventObserver {
constructor() {
this.observers = []
}
subscribe(fn) {
this.observers.push(fn)
}
unsubscribe(fn) {
this.observers = this.observers.filter(subscriber => subscriber !== fn)
}
broadcast(data) {
this.observers.forEach(subscriber => subscriber(data))
}
}
const blogObserver = new EventObserver()
const counstWord = new EventObserver()
const textField = document.querySelector('.textField')
const countField = document.querySelector('.countField')
const getWordsCount = text =>
text ? text.trim().split(/\s+/).length : 0
blogObserver.subscribe(text => {
console.log('broadcast catched 1', text)
})
blogObserver.subscribe(text => {
console.log('broadcast catched 2', text)
})
counstWord.subscribe(text => {
console.log('broadcast catched 3', text)
countField.innerHTML = getWordsCount(text)
})
textField.addEventListener('keyup', () => {
blogObserver.broadcast(textField.value)
})
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<textarea class='textField'></textarea>
<div>
Words Count:
<p class='countField'></p>
</div>
</body>
</html>