Created
August 29, 2017 13:36
-
-
Save jiaming0708/eeb7fb552d14a06690665ba27a013154 to your computer and use it in GitHub Desktop.
observer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var egghead = new Producer(); | |
function listener1(message) { | |
console.log(message + 'from listener1'); | |
} | |
function listener2(message) { | |
console.log(message + 'from listener2'); | |
} | |
egghead.addListener(listener1); // 註冊監聽 | |
egghead.addListener(listener2); | |
egghead.notify('A new course!!') // 當某件事情方法時,執行 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Producer { | |
listeners = []; | |
constructor() { | |
} | |
addListener(listener) { | |
if(typeof listener === 'function') { | |
this.listeners.push(listener) | |
} else { | |
throw new Error('listener 必須是 function') | |
} | |
} | |
removeListener(listener) { | |
this.listeners.splice(this.listeners.indexOf(listener), 1) | |
} | |
notify(message) { | |
this.listeners.forEach(listener => { | |
listener(message); | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment