DEV Community

Tushar Upadhyay
Tushar Upadhyay

Posted on

Simple data emitter and subscriber from scratch in JS

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){

   }
}
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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;
   }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)