Skip to content

Instantly share code, notes, and snippets.

@Silva97
Last active June 12, 2020 18:56
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 Silva97/9924efd5972b284e3f54c88392f6c53a to your computer and use it in GitHub Desktop.
Save Silva97/9924efd5972b284e3f54c88392f6c53a to your computer and use it in GitHub Desktop.
Observer in JS
<!DOCTYPE html>
<html>
<head>
<title>Observer</title>
<script src="./main.js"></script>
<style>
.list {
display: flex;
flex-direction: column;
}
.list img {
width: 150px;
height: 150px;
}
</style>
</head>
<body>
<div class="list">
<input type="text" id="text-field" disabled>
<img src="#" id="img-field">
</div>
<footer id="footer-field"></footer>
</body>
</html>
class Subject {
constructor(data) {
this.list = [];
this.data = data || null;
}
setData(data) {
this.data = data;
this.notify();
}
add(observerList) {
for (let observer of observerList) {
if (typeof observer.update !== 'function') {
throw new Error('Observer must have a `update` method.');
}
this.list.push(observer);
}
}
remove(observer) {
this.list.splice(this.list.indexOf(observer), 1);
}
notify(){
this.list.map(obs => obs.update(this));
}
}
class Observer {
constructor(handler) {
if (typeof handler !== 'function') {
throw new Error('Please, specify a handler function.');
}
this.handler = handler;
}
update(subject) {
this.handler(subject.data);
}
}
const $ = query => document.querySelector(query);
document.addEventListener('DOMContentLoaded', () => {
const textObserver = new Observer(() => {
$('#text-field').disabled = false;
});
const imgObserver = new Observer(data => {
$('#img-field').src = data.args.url;
});
const footerObserver = new Observer(data => {
$('#footer-field').innerHTML = data.args.text;
})
const fetchSubject = new Subject();
fetchSubject.add([textObserver, imgObserver, footerObserver]);
const imgUrl = 'https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Unofficial_JavaScript_logo_2.svg/1200px-Unofficial_JavaScript_logo_2.svg.png';
fetch(`http://httpbin.org/get?url=${imgUrl}&text=Observer`)
.then(response => response.json())
.then(data => fetchSubject.setData(data))
.catch(error => console.error(error));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment