๊ฐ์์(Observer) ํจํด
๐ค ๊ฐ์์(Observer) ํจํด์ ๊ฐ์๊ธฐ ์ ๋์ด์ ?
Angular๋ฅผ ํ๋ค๋ณด๋ฉด Rxjs๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ด ์์ฃผ ๋ง๋ค. ๊ทธ๋ฐ๋ฐ Rxjs๋ฅผ ์์๋ณด๋ค๋ณด๋ฉด Observerํจํด์ ์ด์ฉํ๋ค๊ณ ํ์ฌ ์ด๋ฒ์ ์๋กญ๊ฒ ๊ณต๋ถํด ๋ณด์๋ค.
๐๊ฐ์์(Observer) ํจํด์ด๋?
"A" ๋ผ๋ ๊ฐ์ฒด๊ฐ "B"๋ผ๋ ๊ฐ์ฒด์ ๋ฉ์๋๋ฅผ ์ง์ ํธ์ถํ๋ ๊ฒ์ด ์๋, "B"๊ฐ์ฒด์ ๋ฉ์๋๋ฅผ ๊ฐ์ํ๋ ํจํด์ด๋ค.
๐ค ํ์ํ ๊ฐ์ฒด๋ค
- publish ๊ฐ์ฒด : ๋ฐํ์์ ๊ธฐ๋ฅ์ ๊ฐ์ง๊ณ ์๋ ๊ฐ์ฒด
- paper ๊ฐ์ฒด : ๋ฐํ์์ ๊ธฐ๋ฅ์ ์์(?)๋ฐ๋ ๊ฐ์ฒด
- maxGun๊ฐ์ฒด : paper๊ฐ์ฒด์ ๊ตฌ๋ ์
๐คฉ publish ๊ฐ์ฒด
var publisher = {
//๊ตฌ๋
์๋ฅผ ๊ด๋ฆฌํ๋ ๋ฐฐ์ด
subscribers: {
any: []// '์ด๋ฒคํธ ํ์
: ๊ตฌ๋
์์ ๋ฐฐ์ด'
},
//๊ตฌ๋
์ถ๊ฐ
subscribe(fn, type) {
type = type || 'any';
if (typeof this.subscribers[type] === 'undefined') {
this.subscribers[type] = [];
}
this.subscribers[type].push(fn);
},
//๊ตฌ๋
ํด์
undescribe(fn, type) {
this.visitSubscribers('undescribe', fn, type);
},
//๊ตฌ๋
์๋ค์ด ๋ฑ๋กํ ๋ฉ์๋๋ค์ ํธ์ถ
publish(publication, type) {
this.visitSubscribers('publish', publication, type);
},
visitSubscribers(action, arg, type) {
var pubType = type || 'any',
subscribers = this.subscribers[pubType],
i,
max = subscribers.length;
for (i = 0; i < max; i += 1) {
if (action === 'publish') {
subscribers[i](arg);
} else {
if (subscribers[i] === arg) {
subscribers.splice(i, 1);
}
}
}
}
};
๐ publish ํ๋กํผํฐ ๋ฐ ํจ์ ์ค๋ช
- subscribers : ๊ตฌ๋ ์ ๋ฆฌ์คํธ๋ฅผ ๊ด๋ฆฌํ๊ณ ์๋ publish์ ํ๋กํผํฐ
-
undescribe : ๊ตฌ๋ ์ ๋ฆฌ์คํธ๋ฅผ ์ํํ๋ฉฐ, ๊ตฌ๋ ํด์
-
publish : ๊ตฌ๋ ์ ๋ฆฌ์คํธ๋ฅผ ์ํํ๋ฉฐ, ์ด๋ฒคํธ ํ์ ๊ฐ์ ํจ์ ํธ์ถ
-
visitSubscribers : ๊ตฌ๋ ์ ๋ฆฌ์คํธ๋ฅผ ์ํํ๋ ํจ์
๐ค๋ฐํ์ ์์ฑ
//๋ฐํ์ ์์ฑ
function makePublisher(o) {
var i;
for (i in publisher) {
if (publisher.hasOwnProperty(i) && typeof publisher[i] === "function") {
o[i] = publisher[i];
}
}
o.subscribers = { any: [] };
}
๋ฐํ์ ์์ฑ์ ํตํด ๋ฐํ์์ ๋ฉ์๋๋ค๋ฅผ ์์ ๋ฐ๋๋ก ํ๋๊ฒ์ด๋ค.
๐ Paper ๊ฐ์ฒด ์์ฑ
//paper ๊ฐ์ฒด ์์ฑ
var paper = {
daily(){
this.publish(`big news today`);
},
monthly(){
this.publish(`interesting analysic`,`monthly`);
}
}
๋ฐํ์ ๊ฐ์ฒด๋ฅผ ๋ง๋ค์์ผ๋ฉฐ, daliy๋ฉ์๋์ , monthly๋ฉ์๋๋ฅผ ์์ฑํ์๋ค. ์ฌ๊ธฐ์ this.pulish๋ "publish" ๊ฐ์ฒด์ ์กด์ฌํ๋ ๋ฉ์๋์ด๋ค. ์ฆ ๊ตฌ๋ ์๋ค์ ๋ฉ์๋๋ฅผ ํธ์ถ ํ๋ค๊ณ ๋ณผ ์ ์๋ค.
๐คฉPaper ๋ฅผ ๋ฐํ์๋ก ๋ง๋ค๊ธฐ
//paper๋ฅผ ๋ฐํ์๋ก ๋ง๋ ๋ค.
makePublisher(paper);
๐ถโ๏ธ๊ตฌ๋ ์ ์์ฑ ๋ฐ ๋ฐํ์์ ๊ตฌ๋ ํ ํจ์ ์ถ๊ฐ
//Maxgun ๊ตฌ๋
์ ์์ฑ
var maxGun = {
drinkCoffee(paper){
console.log(`${paper} ๋ฅผ ์ฝ์์ต๋๋ค.`);
},
sundayPreNap(monthly){
console.log(`์ ๋ค๊ธฐ ์ ์ ${monthly}๋ฅผ ์ฝ๊ณ ์์ต๋๋ค.`);
}
}
//๋ฐํ์(paper)๋ maxGun์ ๊ตฌ๋
ํ๋ค
paper.subscribe(maxGun.drinkCoffee);
paper.subscribe(maxGun.sundayPreNap, 'monthly');
์์ ๊ฐ์ด ๋ง๋ค ๊ฒฝ์ฐ ๊ฐ์ฒด๋ค๊ฐ์ ๊ด๊ณ๊ฐ ๋์จํด์ก๋ค. ์ค๋ฌด์์๋ ์ด๋ป๊ฒ ๋ง๋ค์ด์ผํ ์ง ๊ณ ๋ฏผ์ ํด๋ด์ผ ๊ฒ ๋ค.