Skip to content

Instantly share code, notes, and snippets.

@mmiszy
Created May 5, 2016
Embed
What would you like to do?
Observer pattern - simple implementation
/**
* Observer pattern - simple implementation
* By Michał Miszczyszyn, 2016
*/
class Observer {
constructor() {
this.observers = [];
}
addObserver(observer) {
this.observers.push(observer);
}
removeObserver(observer) {
const index = this.observers.indexOf(observer);
if (index === -1) {
return;
}
this.observers.splice(index, 1);
}
notify(data) {
this.observers.forEach(observer => {
observer(data);
});
}
}
describe('Observer', () => {
it('should observe changes', () => {
const observer = new Observer();
const callback1 = jasmine.createSpy('callback1');
const callback2 = jasmine.createSpy('callback2');
observer.addObserver(callback1);
observer.addObserver(callback2);
observer.notify('test1');
expect(callback1).toHaveBeenCalledWith('test1');
expect(callback2).toHaveBeenCalledWith('test1');
});
it('should remove observer', () => {
const observer = new Observer();
const callback1 = jasmine.createSpy('callback1');
const callback2 = jasmine.createSpy('callback2');
const callback3 = jasmine.createSpy('callback3');
observer.addObserver(callback1);
observer.addObserver(callback2);
observer.addObserver(callback3);
observer.removeObserver(callback2);
observer.notify('test1');
expect(callback1).toHaveBeenCalledWith('test1');
expect(callback3).toHaveBeenCalledWith('test1');
expect(callback2).not.toHaveBeenCalled();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment