Make writing a habit together! This is the fifth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.


Cut the chatter and go straight!

Use javascript to write a search function:

<input id="text"></input> <script> var text = document.querySelector('#text'); text.addEventListener('keyup', (e) =>{ var searchText = e.target.value; $. Ajax ({// send request url: 'search.qq.com/${searchText}', success: data => {render(data); // Process data}}); }); </script>Copy the code

Search is to do anti-shake processing, a simple version of anti-shake is as follows:

<input id="text"></input> <script> var text = document.querySelector('#text'), timer = null; text.addEventListener('keyup', (e) =>{ clearTimeout(timer); Timer = setTimeout(() => {console.log(' Initiate a request.. '); },300) // 300 milliseconds after trigger; }) </script>Copy the code

So, the search function evolved to:

<input id="text"></input> <script> var text = document.querySelector('#text'), timer = null, currentSearch = ''; text.addEventListener('keyup', (e) =>{ clearTimeout(timer) timer = setTimeout(() => { var searchText = e.target.value; $.ajax({ url: `search.qq.com/${searchText}`, success: data => { render(data); }}); },300) }) </script>Copy the code

Right? It’s routine. But the actual business tends to be much bigger than the code in the example, and along the lines above, you end up with something like this:

It’s no exaggeration.

At this time, can only sacrifice the ultimate solution: this protagonist — RxJS, in fact, there are more than JS RxJS, and its corresponding, RxJava, RxAndroid, RxSwift, they are processing asynchronous programming [nuclear Arsenal];

RxJS implementation:

import { fromEvent } from 'rxjs';
import { debounceTime, pluck, switchMap } from 'rxjs/operators';

var text = document.querySelector('#text');
var inputStream = Rx.Observable.fromEvent(text, 'keyup')
                    .debounceTime(300)
                    .pluck('target', 'value')
                    .switchMap(url => Http.get(url))
                    .subscribe(data => render(data));
Copy the code

Let’s break down its API one by one:

  • fromEvent

FromEvent is used to convert events into Observables (an enhanced version of promises for those who don’t know what an Observable is).

In short, observables that create click times say something like this:

const source = fromEvent(document, 'click');

  • debounceTime

This is easy to understand, for the event to add anti-shake, the parameter is the anti-shake time;

Discard output values that are less than the specified time between outputs.

U1s1, the explanation is hard to read. (For those of you who still don’t understand what anti-shaking is, it can be understood as a return trip in LOL. Press B and you will return to the city after a few seconds. If you press B all the time, you will not return to the city.)

  • pluck

Select properties to emit;

Such as:

const source = from([{ name: 'Joe', age: 30 }, { name: 'Sarah', age: 35 }]); // Pluck name const example = source.pipe(pluck('name')); // output: "Joe", "Sarah" const subscribe = example.subscribe(val => console.log(val));Copy the code

In the search case, it is the event. Target. Value that extracts the click

  • switchMap

SwitchMap;

Map to Observable, complete the previous internal Observable, and emit values.

Yeah, still hard to get ZZZ

Instead, put it another way:

In RxJS, a pinball diagram is commonly used to represent “event flow”. For example, the pinball diagram of the MAP API is as follows:

The switch API pinball diagram looks like this:

When issuing a new internal Observable, the Switch unsubscribes from the previously sent internal Observable, subscribes to the new internal Observable and starts emitting its values.

Always subscribe to the latest Observable;

SwitchMap = map + switch, as follows:

Combined with understanding, in this search example, the data value obtained by HTTP. get(URL) is used as the latest value of the event stream for subsequent transmission;

At this point, we can conclude that RxJS makes code very concise and readable, provided we are familiar with the event stream and its API


OK, the above is the share, hope you can help ~ feel good, give a three link bar 👍👍👍

I’m Nuggets Anthony, output exposure input, technical insight into life.