Have to ever used a Reactive setup in JS?Lets try to make it from scratch
So if you have used any reactive stuff in JS, it mainly contains two methods, one for emitting the data and one for listen the changes by subscribing to it.
Lets say we have a class CustomRxm, So it should have two methods emit and subscribe
class CustomRx{
constructor(initialData:string){
this.data = initialData;
}
emit(data:string){
}
subscribe(callback:Function){
}
}
We will going to use these methods like:
const rx = new CustomRx('tushar');
rx.subscribe((data:string)=>{
console.log(data)
})
rx.emit('new name');
rx.emit('some new data');
Lets code these methods:-
See we are getting a callback function as an argument in subscribe method.The trick is to store this as class variable and call this in emit method with new data as argument.
(Since this is a simple example this will only work with one subscriber)
class CustomRx{
constructor(initialData:string){
this.data = initialData;
}
emit(data:string){
this.data = data;
this.callback(this.data);
}
subscribe(callback:Function){
this.callback = callback;
}
}
In action:-
const rx = new CustomRx('tushar');
rx.subscribe((data:string)=>{
console.log(data)
})
setInterval(()=>{
rx.emit('new name');
},1000)
// 'new name' will be printed out in console each 1 second
Top comments (0)