Last active
May 15, 2017 17:29
-
-
Save ramzesucr/e62a30a633afd165d23ca65134cb02db to your computer and use it in GitHub Desktop.
DesignPatters: Observer (javascript)
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
function User() { | |
this.subscribers = [] | |
} | |
User.prototype.subscribe = function(subscriber) { | |
this.subscribers.push(subscriber) | |
} | |
User.prototype.unsubscribe = function(subscriber) { | |
this.subscribers = this.subscribers.filter((item) => { | |
return item !== subscriber | |
}) | |
} | |
User.prototype.walk = function(meters) { | |
this.subscribers.forEach((subscriber) => { | |
subscriber.call(this, meters) | |
}) | |
} | |
function run() { | |
let user = new User() | |
let subscriber1 = function(meters) { | |
console.log('subscriber1', 'user walk', meters, 'meters') | |
} | |
user.subscribe(subscriber1) | |
let subscriber2 = function(meters) { | |
console.log('subscriber2', 'user walk', meters, 'meters') | |
} | |
user.subscribe(subscriber2) | |
user.walk(5) | |
user.unsubscribe(subscriber1) | |
user.walk(10) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment