Skip to content

Commit

Permalink
Observer
Browse files Browse the repository at this point in the history
  • Loading branch information
Sparragus committed Jul 19, 2019
1 parent 8b82b83 commit efffff0
Show file tree
Hide file tree
Showing 4 changed files with 101 additions and 0 deletions.
16 changes: 16 additions & 0 deletions ejercicios/decorator/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<html>
<head>
<title>Decorator</title>
</head>

<body>
<a href="/ejercicios/">Go back</a>

<div style="margin-top: 3rem;">
<label for="email">Email</label>
<input id="email" />
</div>

<script src="/ejercicios/decorator/index.ts"></script>
</body>
</html>
28 changes: 28 additions & 0 deletions ejercicios/decorator/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Field {
errors: string[];
input: HTMLInputElement;

constructor(input: HTMLInputElement) {
this.input = input;
this.errors = [];

let errorMessage = document.createElement('p');
errorMessage.className = 'text-danger';
this.input.parentNode.insertBefore(errorMessage, this.input.nextSibling);

this.input.addEventListener('input', () => {
this.errors = [];
this.validate();
errorMessage.innerText = this.errors[0] || '';
});
}

validate() {}
}

function RequiredFieldDecorator(field: Field) {
return field;
}

let field = new Field(document.querySelector('#email'));
RequiredFieldDecorator(field);
3 changes: 3 additions & 0 deletions ejercicios/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ <h1>Índice</h1>
<li>
<a href="/ejercicios/observer/index.html">Observer</a>
</li>
<li>
<a href="/ejercicios/decorator/index.html">Decorator</a>
</li>
</ol>
</body>
</html>
54 changes: 54 additions & 0 deletions ejercicios/observer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
interface Observer {
update: (data: any) => void;
}

interface Subject {
subscribe: (observer: Observer) => void;
unsubscribe: (observer: Observer) => void;
}

class BitcoinPrice implements Subject {
observers: Observer[] = [];

constructor() {
const el: HTMLInputElement = document.querySelector('#value');
el.addEventListener('input', () => {
this.notify(el.value);
});
}

subscribe(observer: Observer) {
this.observers.push(observer);
}

unsubscribe(observer: Observer) {
const index = this.observers.findIndex(obs => {
return obs === observer;
});

this.observers.splice(index, 1);
}

notify(data: any) {
this.observers.forEach(observer => observer.update(data));
}
}

class PriceDisplay implements Observer {
private el: HTMLElement;

constructor() {
this.el = document.querySelector('#price');
}

update(data: any) {
this.el.innerText = data;
}
}

const value = new BitcoinPrice();
const display = new PriceDisplay();

value.subscribe(display);

setTimeout(() => value.unsubscribe(display), 5000);

0 comments on commit efffff0

Please sign in to comment.