Skip to content

Instantly share code, notes, and snippets.

@velotiotech
Created August 19, 2020 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save velotiotech/06814919d613a19c19bed4c04ec92fec to your computer and use it in GitHub Desktop.
Save velotiotech/06814919d613a19c19bed4c04ec92fec to your computer and use it in GitHub Desktop.
// Publisher
class Video {
constructor(observable, name, content) {
this.observable = observable;
this.name = name;
this.content = content;
// publish the ‘video-uploaded’ event
this.observable.publish('video-uploaded', {
name,
content,
});
}
}
// Subscriber
class User {
constructor(observable) {
this.observable = observable;
this.intrestedVideos = [];
// subscribe with the event naame and the call back function
this.observable.subscribe('video-uploaded', this.addVideo.bind(this));
}
addVideo(video) {
this.intrestedVideos.push(video);
}
}
// Observer
class Observable {
constructor() {
this.handlers = [];
}
subscribe(event, handler) {
this.handlers[event] = this.handlers[event] || [];
this.handlers[event].push(handler);
}
publish(event, eventData) {
const eventHandlers = this.handlers[event];
if (eventHandlers) {
for (var i = 0, l = eventHandlers.length; i < l; ++i) {
eventHandlers[i].call({}, eventData);
}
}
}
}
// usage
const observable = new Observable();
const user = new User(observable);
const video = new Video(observable, 'ES6 Design Patterns', videoFile);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment