In the previous article I explained what I mean when I say Reactive.

In this article I'm going to dig a little deeper and get a little more concrete with a simple example.

Configuration

These examples use TypeScript, so if you're using CodePen.io (which I suggest, at least for the first few examples until we start putting together a full stack application) then change your JavaScript settings to use the TypeScript pre-processor, and also add the RxJS external script:

https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js

Sample Code

For starters, lets create a simple HTML page with the following body:

<label for="firstName">First Name</label>
<input type="text" id="firstName"></input>

And lets add the following code:

const { fromEvent } = rxjs;
const { map } = rxjs.operators;

var firstName: Observable<string> = fromEvent(document.querySelector('#firstName'), 'input')
  .pipe(map(event => event.target.value));

firstName
  .subscribe((value: string) => console.log(value));

Explanation

In this example, the firstName variable is an observable string value which changes every time the user changes the value of the firstName input text box.

Breaking it down in more detail:

  • document.querySelector('#firstName') gets the input text box DOM element.
  • fromEvent(domElement, 'input') creates an observable on the input event for the specified domElement.

At this point, if you had stopped there, then subscribing to the observable would pass the event to the observer. As it is, this event is what is also passed to the pipeline.

  • .pipe() creates a pipeline with a list of operators.
  • map(event => event.target.value) operator converts the event to the string value, so any subsequent pipeline operators will be operating on the string value, not the original event.

The next section of code subscribes to the Observable<string> and sends the string to the console.log function.

firstName
  .subscribe((value) => console.log(value));

When you run this full example, every time you change the value of the input text box, the new value is displayed in the console.

If you want to play with this, check it out on CodePen.