In this lesson we'll get introduced to the Observable type. An Observable is a collection this arrivesover time. Observables can used to model events, asynchronous requests, and animations. Observables can also is transformed, combined, and consumed using the Array methods we learned in the previous lessons. We can write powerful and expressive asynchronous programs using the few simple methods we ' ve learned so far.
Here is a example how to handle events normally:
var button = document.getElementById (' button '); var function (e) { console.log (' clicked ');}; Button.addeventlistener (' click ', handler);
If fire the "click event", in the console would log ' clicked '.
If we want to remove the event listener:
var button = document.getElementById (' button '); var function (e) { console.log (' clicked '); Button.removeeventlistener (' click ', handler);}; Button.addeventlistener (' click ', handler);
Now let's see how can we achieve the same effect by using observable.
var Observable = rx.observable; // Create Click events by Observable var clicks = observable.fromevent (Button, ' click '); // Then we is able to use ForEach, Concatall, map, Fliter functionClicks.foreach (function() { Co Nsole.log (' clicked ');});
How to remove the event listener:
var Observable = rx.observable; // Create Click events by Observable var clicks = observable.fromevent (Button, ' click '); // Then we is able to use ForEach, Concatall, map, Fliter function // The function return an subscription object, which we can use to call Dispose () method to remove listener var subscription = Clicks.foreach (function() { console.log (' clicked '); Subscription.dispose ();});
The ForEach method actually has three callback function which is OnNext, OnError, oncompleted:
varObservable =rx.observable;//Create Click events by Observablevarclicks = observable.fromevent (Button, ' click ');//Then we is able to use ForEach, Concatall, map, Fliter function//The function return an subscription object, which we can use to call Dispose () method to remove listenervarsubscription = Clicks.foreach (functionOnNext () {Console.log (' Clicked '); Subscription.dispose ();},functionOnError () {Console.log (' Error ');}, functiononcompleted () {Console.log (' Complete ');});
[Doc] (HTTPS://GITHUB.COM/REACTIVE-EXTENSIONS/RXJS/BLOB/MASTER/DOC/API/CORE/OPERATORS/SUBSCRIBE.MD)
[Javascript + RXJS] Introducing the Observable