Implement observable
by Saksham Malhotra
JavaScript
class Observable {
element = '';
constructor(element){
this.funcArray = [];
this.element = element;
}
get(){
return this.element
}
set(element){
this.element = element;
this.funcArray.forEach(func => func(element));
}
subscribe(func){
this.funcArray.push(func);
}
}
class Computed {
constructor(computeFunc){
this.computeFunc = computeFunc
firstName.subscribe(newVal => {
this.fullname = computeFunc()
});
lastName.subscribe(newVal => {
this.fullname = computeFunc()
});
}
get(){
return this.computeFunc();
}
subscribe(func) {
func(this.fullName)
}
}
const myObs = new Observable('hello');
myObs.get(); // returns "hello"
myObs.subscribe((newVal) => {
console.log(newVal);
});
myObs.set('hi'); // alert("hi")
const firstName = new Observable('Joe');
const lastName = new Observable('Liner');
const fullName = new Computed(() => {
return firstName.get() + ' ' + lastName.get();
})
fullName.get(); // Joe Liner'
fullName.subscribe((newVal) => { console.log(newVal) });
firstName.set('Bob');
lastName.set('Smith');