RxJs Book
  • Introduction
  • Summary
    • Why RxJS?
    • RxJS Design Guidelines
      • Introduction
      • When To Use RxJS
      • The RxJS Contract
      • Using RxJS
      • Operator Implementations
    • Getting Started With RxJS
      • What Are The Reactive Extensions?
      • Exploring Major Concepts In RxJS
      • Creating And Querying Observable Sequences
        • Creating And Subscribing To Simple Observable Sequences
        • Bridging To Events
        • Bridging To Callbacks
        • Bridging To Promises
        • Generators And Observable Sequences
        • Querying Observable Sequences
        • Error Handling With Observable Sequences
        • Transducers With Observable Sequences
        • Backpressure With Observable Sequences
        • Operators By Category
      • Subjects
      • Scheduling And Concurrency
      • Testing And Debugging
      • Implementing Your Own Operators
    • How Do I...?
      • How Do I Wrap An Existing API?
      • How Do I Integrate jQuery With RxJS?
      • How Do I Integrate Angular.js With RxJS?
      • How Do I Create A Simple Event Emitter?
    • Mapping RxJS From Different Libraries
      • For Bacon.js Users
      • For Async.js Users
    • Config
      • Promise
      • useNativeEvents
    • Helpers
      • defaultComparer
      • defaultSubComparer
      • defaultError
      • identity
      • just
      • isPromise
      • noop
      • pluck
    • Observable
      • Observable Methods
        • amb
        • case
        • catch
        • combineLatest
        • concat
        • create
        • defer
        • empty
        • for | forIn
        • forkJoin
        • from
        • fromCallback
        • fromEvent
        • fromEventPattern
        • fromNodeCallback
        • fromPromise
        • generate
        • generateWithAbsoluteTime
        • generateWithRelativeTime
        • if
        • interval
        • isObservable
        • just | return
        • merge
        • mergeDelayError
        • never
        • of
        • ofWithScheduler
        • onErrorResumeNext
        • pairs
        • range
        • repeat
        • spawn
        • start
        • startAsync
        • throw
        • timer
        • toAsync
        • using
        • when
        • while | whileDo
        • wrap
        • zip
      • Observable Instance Methods
        • amb
        • and
        • asObservable
        • average
        • buffer
        • bufferWithCount
        • bufferWithTime
        • bufferWithTimeOrCount
        • catch
        • combineLatest
        • concat
        • concatAll
        • concatMapObserver | selectConcatObserver
        • controlled
        • count
        • debounce
        • defaultIfEmpty
        • delay
        • delaySubscription
        • dematerialize
        • distinct
        • distinctUntilChanged
        • do | doAction | tap
        • doOnCompleted | tapOnCompleted
        • doOnError | tapOnError
        • doOnNext | tapOnNext
        • doWhile
        • elementAt
        • every
        • expand
        • extend | manySelect
        • filter | where
        • finally
        • find
        • findIndex
        • first
        • flatMap | selectMany
        • flatMapConcat | concatMap
        • flatMapFirst | selectSwitchFirst
        • flatMapLatest
        • flatMapObserver | selectManyObserver
        • flatMapWithMaxConcurrent
        • forkJoin
        • groupBy
        • groupByUntil
        • groupJoin
        • ignoreElements
        • includes
        • indexOf
        • isEmpty
        • join
        • jortSort
        • jortSortUntil
        • last
        • lastIndexOf
        • let | letBind
        • map | select
        • materialize
        • max
        • maxBy
        • merge
        • mergeAll
        • min
        • minBy
        • multicast
        • observeOn
        • onErrorResumeNext
        • pairwise
        • partition
        • pausable
        • pausableBuffered
        • pipe
        • pluck
        • publish
        • publishLast
        • publishValue
        • reduce
        • repeat
        • replay
        • retry
        • retryWhen
        • scan
        • sequenceEqual
        • share
        • shareReplay
        • shareValue
        • single
        • singleInstance
        • skip
        • skipLast
        • skipLastWithTime
        • skipUntil
        • skipUntilWithTime
        • skipWhile
        • skipWithTime
        • slice
        • some
        • startWith
        • subscribe | forEach
        • subscribeOn
        • subscribeOnCompleted
        • subscribeOnError
        • subscribeOnNext
        • sum
        • switch
        • switchFirst
        • take
        • takeLast
        • takeLastBuffer
        • takeLastBufferWithTime
        • takeLastWithTime
        • takeUntil
        • takeUntilWithTime
        • takeWhile
        • takeWithTime
        • thenDo
        • throttle
        • throttleLatest | sample
        • timeInterval
        • timeout
        • timestamp
        • toArray
        • toMap
        • toPromise
        • toSet
        • transduce
        • window
        • windowWithCount
        • windowWithTime
        • windowWithTimeOrCount
        • withLatestFrom
        • zip
        • zipIterable
    • Observer
      • Observer Methods
        • create
        • fromNotifier
      • Observer Instance Methods
        • asObserver
        • checked
        • notifyOn
        • onCompleted
        • onError
        • onNext
        • toNotifier
    • Notification
      • Notification Methods
        • createOnNext
        • createOnError
        • createOnCompleted
      • Notification Instance Methods
        • accept
        • toObservable
      • Notification Properties
        • exception
        • hasValue
        • kind
        • value
    • Subjects
      • Rx.AsyncSubject
      • Rx.BehaviorSubject
      • Rx.ReplaySubject
      • Rx.Subject
    • Schedulers
      • Rx.HistoricalScheduler
      • Rx.Scheduler
      • Rx.VirtualTimeScheduler
    • Disposables
      • Rx.CompositeDisposable
      • Rx.Disposable
      • Rx.RefCountDisposable
      • Rx.SerialDisposable
      • Rx.SingleAssignmentDisposable
    • Testing
      • Rx.ReactiveTest
      • Rx.Recorded
      • Rx.Subscription
      • Rx.TestScheduler
    • Bindings
      • DOM
        • Ajax
          • ajax
          • ajaxCold
          • get
          • get_Json
          • post
        • JSONP
          • jsonpRequest
          • jsonpRequestCold
        • Web Sockets
          • fromWebSocket
        • Web Workers
          • fromWebWorker
        • Mutation Observers
          • fromMutationObserver
        • Geolocation
          • getCurrentPosition
          • watchPosition
        • Schedulers
          • requestAnimationFrame
          • mutationObserver
      • jQuery
      • AngularJS
        • Factories
          • rx
          • observeOnScope
        • Observable Methods
          • safeApply
        • $rootScope Methods
          • $toObservable
          • $eventToObservable
          • $createObservableFunction
      • Facebook React
      • Ractive.js
      • Node.js
        • Callback Handlers
          • fromCallback
          • fromNodeCallback
        • Event Handlers
          • fromEvent
          • toEventEmitter
        • Stream Handlers
          • fromStream
          • fromReadableStream
          • fromWritableStream
          • fromTransformStream
          • writeToStream
  • Recipes
  • Which Operator do I use?
    • Creation Operators
    • Instance Operators
Powered by GitBook
On this page
  • Using RxJS with Rx-jQuery ##
  • Using RxJS with jQuery ##
  • Binding to an event ###
  • Using RxJS with Ajax calls ###
  • Using RxJS with Callbacks to Handle Simple Animations ###

Was this helpful?

  1. Summary
  2. How Do I...?

How Do I Integrate jQuery With RxJS?

PreviousHow Do I Wrap An Existing API?NextHow Do I Integrate Angular.js With RxJS?

Last updated 5 years ago

Was this helpful?

The project and RxJS play very well together as libraries. In fact, we supply bindings directly for RxJS to jQuery should you want to wrap animations, events, Ajax calls and more using Observables in . The bindings library provides many handy features for bridging the world to Observables. If you're interested in that library, go ahead and use it.

Using RxJS with Rx-jQuery ##

Getting started with the bindings is easy. Each method is enumerated on the main page from the jQuery method to its RxJS counterpart.

<div id="results"></div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="rx.js"></script>
<script src="rx.binding.js"></script>
<script src="rx.jquery.js"></script>

Now we can start using the bindings! For example, we can listen to a click event and then by using flatMap or selectMap we can animate by calling animateAsObservable. Finally, we can subscribe to cause the side effect and nothing more.

$( "#go" ).clickAsObservable().flatMap(() => {

    return $( "#block" ).animateAsObservable({
        width: "70%",
        opacity: 0.4,
        marginLeft: "0.6in",
        fontSize: "3em",
        borderWidth: "10px"
    }, 1500 );
}).subscribe();

Using RxJS with jQuery ##

Let's start though by assuming you just have RxJS and wanted to get started with jQuery without the bridge library. There is already plenty you can do without even needing a bridge library with the support built in for events and promises.

Binding to an event ###

Using RxJS with jQuery to bind to an event using plain old RxJS is easy. For example, we could bind to the mousemove event from the DOM document easily.

First, we'll reference the files we need.

<div id="results"></div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="rx.js"></script>
<script src="rx.async.js"></script>
<script src="rx.binding.js"></script>
var observable = Rx.Observable.fromEvent(
    $(document),
    'mousemove');

var subscription = observable.subscribe(e => $('#results').text(e.clientX + ',' + e.clientY));

We could go a step further and create our own jQuery plugin which handles events with ease.

/**
 * Creates an observable sequence by adding an event listener to the matching jQuery element
 *
 * @param {String} eventName The event name to attach the observable sequence.
 * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
 * @returns {Observable} An observable sequence of events from the specified element and the specified event.
 */
jQuery.fn.toObservable = function (eventName, selector) {
    return Rx.Observable.fromEvent(this, eventName, selector);    
};

Now we could rewrite our above example such as this.

var observable = $(document).toObservable('mousemove');

var subscription = observable.subscribe(e => $('#results').text(e.clientX + ',' + e.clientY));

Using RxJS with Ajax calls ###

function searchWikipedia (term) {
    var promise = $.ajax({
        url: 'http://en.wikipedia.org/w/api.php',
        dataType: 'jsonp',
        data: {
            action: 'opensearch',
            format: 'json',
            search: encodeURI(term)
        }
    }).promise();
    return Rx.Observable.fromPromise(promise);
}

Once we created the wrapper, we can query the service by getting the text and then using flatMapLatest to ensure we have no out of order results.

$('#input').toObservable('keyup')
    .map(e => e.target.value;)
    .flatMapLatest(searchWikipedia)
    .subscribe(data => {

        var results = data[1];

        $.each(results, (_, result) => {
            // Do something with each result
        });

    });

Using RxJS with Callbacks to Handle Simple Animations ###

You'll note that we need a notion of this for the block.animate to properly work, so we have two choices, either use Function.prototype.bind available in most modern browsers...

var animate = Rx.Observable.fromCallback(block.animate.bind(block));

Or we can supply an optional argument which supplies the context to the callback such as the following...

var animate = Rx.Observable.fromCallback(
    block.animate,
    null, /* default scheduler used */
    block /* context */);

When viewed in its entirety, it will look like this where we call flatMap or selectMany to compose together two observable sequences. We then bind to the animate function through Rx.Observable.fromCallback and then return the observable which results from the function execution. Our subscribe does nothing in this case as there is nothing to print or do, and is simply a side effect.

var block = $('#block');

$('#go').toObservable('click').flatMap(() => {
    var animate = Rx.Observable.fromCallback(block.animate.bind(block));

    return animate({
        width: "70%",
        opacity: 0.4,
        marginLeft: "0.6in",
        fontSize: "3em",
        borderWidth: "10px"
    }, 1500);
}).subscribe();

Bridging to jQuery Ajax calls using is easy as well with the built-in support. Since jQuery 1.5, the $.ajax method has implemented a promise interface (even if not 100% pure) which allows us to bridge to an observable sequence via the Rx.Observable.fromPromise method.

For example, we could query Wikipedia by calling the $.ajax method and then calling the method which then exposes the minimum promise interface needed.

RxJS can also be used to bind to simple callbacks, such as the method. We can use Rx.Observable.fromCallback to supply the required arguments with the last argument is to be the callback. In this example, we'll take the animation example from above and use nothing but core RxJS to accomplish the same thing.

jQuery
RxJS-jQuery
$.ajax
Promises A+
promise
.animate()