LoginSignup
2
2

More than 5 years have passed since last update.

How to use a single Rx.Observable instead of a billion jQuery event handlers for the same event

Last updated at Posted at 2015-04-17

I made this simple demo because all the RxJS tutorials are way too hard/dense -- it's like trying to teach someone how to use an electronic microscope without ever letting them look at pictures. I just want to see something simple on my screen!

Also, smarter people than me have preferred to call Rx.Observable objects "Streams", so you may prefer that term in the end.

JSBin here: http://jsbin.com/wawoqe/edit?js,output

Otherwise, content here:

"Content"

/*
 * RxJS tutorials are way too hard, I just want to see the simplest possible thing work!
 * There is some philosophical crap about a stream of events just being a list of values,
 * but you can drink the antifreeze on your own.
 *
 * Thus, this really crappy demo was born.
 */

/*
 * Create the observable from an event, in this case, the window scroll event
 * then map each event so we can get a new value from it
 * i.e. over time, we are just dealing with a collection:
 * (map [e1, e2, e3, ...]) -> [t1, t2, t3, ...]
 */
var windowYOffsetObservable = Rx.Observable.fromEvent(window, 'scroll').map(function () {
  // I don't actually care about the event, I just need to get the window offset (scroll position)
  return window.pageYOffset;
});

// subscribe to our Observable so that for each new item, our callback runs
// this is our event handler, except that it doesn't cost us an arm and a leg
var consoleOutSubscription = windowYOffsetObservable.subscribe(function (input) {
  console.log(input);
});

// these next subscriptions manipulate the innerText of our a,b,c,d elements
var aBlockSubscription = windowYOffsetObservable.subscribe(function (input) {
  a.innerText = "The input is now " + input;
});

var bBlockSubscription = windowYOffsetObservable.subscribe(function (input) {
  b.innerText = "2 * input is now " + 2 * input;
});

var cBlockSubscription = windowYOffsetObservable.subscribe(function (input) {
  c.innerText = "3 * input is now " + 3 * input;
});

var dBlockSubscription = windowYOffsetObservable.subscribe(function (input) {
  d.innerText = "4 * input is now " + 4 * input;
});

/*
 * and then when we're done, we would dispose of these:
 *
 *   aBlockSubscription.dispose();
 *
 * which is much cleaner and easier than trying to hold on to your callbacks
 *
 *   $(window).on('scroll', callback); // hope you got a reference to this somewhere...
 *   $(window).off('scroll', callback); // forgot to do this? start the profiler 
 *                                      // and watch your resources go crazy
 *
 * Congrats, now you can go forth and write some code and read all the RxJS docs and staltz
 * tutorials later.
 */

"Flowchart" for "basic usage"

 Rx.Observable[fromWhatever]    OurObservable[whateverTransform]    Rx.Observable.prototype.subscribe
    Rx.Observable                     Rx.Observable                         Rx.Disposable
---------------------    ---------------------------------------    ---------------------------
| Create Observable | -> | Get new Observable using transforms | -> | subscribe to Observable |
---------------------    ---------------------------------------    ---------------------------
                                                                                 |
                     |-----------------------------------------------------------|
                     |
                     |                                                 Rx.Disposable.prototype.dispose
                     |                                                         undefined                        
                     |     -----------------------------------------    ------------------------
                     |---> | subscribed callbacks happen per event | -> | dispose subscription |         
                           -----------------------------------------    ------------------------

You're probably much better off reading ball diagrams (http://reactivex.io/documentation/observable.html).

Better resources

RxJS README: https://github.com/Reactive-Extensions/RxJS/blob/master/readme.md

The staltz intro to Reactive Programming: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2