-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #7 from shubhamgautam89/pattern/observer
observer patternn
- Loading branch information
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
/* | ||
* With the observer pattern, we can subscribe certain objects, the observers, to another object, called the observable. Whenever an event occurs, the observable notifies all its observers! | ||
*/ | ||
|
||
class Observable { | ||
constructor() { | ||
this.observers = []; | ||
} | ||
|
||
subscribe(f) { | ||
this.observers.push(f); | ||
} | ||
|
||
unsubscribe(f) { | ||
this.observers = this.observers.filter((subs) => subs !== f); | ||
} | ||
|
||
notify(data) { | ||
this.observers.forEach((observer) => observer(data)); | ||
} | ||
} | ||
|
||
export default Observable; |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import Observable from "./observer"; | ||
|
||
describe("Observable", () => { | ||
let observable; | ||
beforeEach(() => { | ||
observable = new Observable(); | ||
}); | ||
|
||
test("subscribes a function and notiofies it", () => { | ||
const mockFunction = jest.fn(); | ||
observable.subscribe(mockFunction); | ||
observable.notify("test-data"); | ||
|
||
expect(mockFunction).toHaveBeenCalledWith("test-data"); | ||
}); | ||
|
||
test("unsubscirbes a function and does not notify it", () => { | ||
const mockFunction = jest.fn(); | ||
observable.subscribe(mockFunction); | ||
observable.unsubscribe(mockFunction); | ||
|
||
observable.notify("test-data"); | ||
|
||
expect(mockFunction).not.toHaveBeenCalled(); | ||
}); | ||
|
||
test("notifies only subscribed function", () => { | ||
const mockFunction1 = jest.fn(); | ||
const mockFunction2 = jest.fn(); | ||
|
||
observable.subscribe(mockFunction1); | ||
observable.notify("test-data"); | ||
|
||
expect(mockFunction1).toHaveBeenCalledWith("test-data"); | ||
expect(mockFunction2).not.toHaveBeenCalled(); | ||
}); | ||
}); |