Last active
March 10, 2020 03:17
-
-
Save avtarnanrey/e0481624a4612d6f23e6ee4036f54fa6 to your computer and use it in GitHub Desktop.
JavaScript Patterns: Observer Pattern
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
// ES5 example | |
function Subject () { | |
this.observers = []; // Array of observer functions | |
} | |
Subject.prototype = { | |
subscribe: function (fn) { | |
this.observers.push(fn) | |
}, | |
unsubscribe: function (fn) { | |
this.observers = this.observers.filter(f => f !== fn); | |
}, | |
fire: function () { | |
this.observers.forEach( f => f()) | |
} | |
} | |
// In action | |
const subject = new Subject(); | |
function Observer1 () { | |
console.log("Observer 1 is Firing!") | |
} | |
function Observer2 () { | |
console.log("Observer 2 is Firing!") | |
} | |
// subscribe | |
subject.subscribe(Observer1); | |
subject.subscribe(Observer2); | |
// unsubscribe | |
subject.unsubscribe(Observer1); | |
// Fire it | |
subject.fire(); | |
/** | |
* ES6 Class * | |
**/ | |
class State { | |
observers = []; | |
constructor (state, fn) { | |
this.state = state; | |
fn && this.observers.push(fn); | |
} | |
} | |
class Subject extends State { | |
constructor (state) { | |
super(state); | |
} | |
get getState () { | |
return this.state; | |
} | |
set setState (newState) { | |
this.state = newState; | |
this.fire() | |
} | |
set subscribe (fn) { | |
this.observers.push(fn); | |
} | |
set unsubscribe (fn) { | |
this.observers.filter(f => f !== fn); | |
} | |
fire () { | |
this.observers.forEach(fn => fn()); | |
} | |
} | |
function Observer1 () { | |
console.log("Observer 1 Firing"); | |
} | |
function Observer2 () { | |
console.log("Observer 2 Firing"); | |
} | |
let subject = new Subject(); | |
subject.subscribe = Observer1; | |
subject.subscribe = Observer2; | |
subject.setState = "test"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment