Hi I\'m tyring to implement observer pattern in JavaScript:
My index.js:
$(document).ready(function () {
var ironMan = new Movie();
class Observable {
constructor() {
this.observer = [];
}
subscribe(item) {
this.observer.push(item);
}
unsubscribe(item) {
if(!this.observer) return 'empty';
else {
this.observer.filter(subscribe => subscribe !== item);
}
}
notify(data) {
this.observer.forEach(item => item(data));
}
}
var p1 = document.querySelector('.p1');
var p2 = document.querySelector('.p2');
var p3 = document.querySelector('.p3');
var input = document.querySelector('.input');
const update1 = text => p1.textContent = text;
const update2 = text => p2.textContent = text;
const update3 = text => p3.textContent = text;
var observarble = new Observable();
observarble.subscribe(update1);
observarble.subscribe(update2);
observarble.subscribe(update3);
input.addEventListener('keyup', event => observarble.notify(event.target.value));
Observer is one of the popular patterns that use across all javascript applications.
The instance (subject) maintains a collection of objects (observers) and notifies them all when changes to the state occur.
Let's explain by writing some logic
class Observable {
constructor() {
this.observer = [];
}
subscribe(item) {
this.observer.push(item);
}
unsubscribe(item) {
if(!this.observer) return 'empty';
else {
this.observer.filter(subscribe => subscribe !== item);
}
}
notify(data) {
this.observer.forEach(item => item(data));
}
}
Now your question will be what's next ??
Where to actually use this pattern.
Imagine that you have to update multiple elements simultaneously when some event occurs.
Add some HTML in your code
Get those nodes using Javascript
var p1 = document.querySelector('.p1');
var p2 = document.querySelector('.p2');
var p3 = document.querySelector('.p3');
var input = document.querySelector('.input');
To set the value using observer you need to add their text content
const update1 = text => p1.textContent = text;
const update2 = text => p2.textContent = text;
const update3 = text => p3.textContent = text;
var observarble = new Observable();
observarble.subscribe(update1);
observarble.subscribe(update2);
observarble.subscribe(update3);
One last thing attach an event listener with input keyup/change
input.addEventListener('keyup', ev => observarble.notify(ev.target.value));
That's it :) !!
Link for working demo https://codepen.io/nishant5857/pen/MWKdByY