Although there are many sources where you can learn about it from they don’t have a structured guide to help you get started and some of the info/demo I found were pretty out-dated and not in line with the latest API. Among the articles I’ve read so far I found the series of articles by Matthew Podwysocki on codebetter.com to be most useful and definitely worth reading through if you want get up to speed with RXJS.
Anyways, back to the point of the post, I just wanted to show you how to achieve a simple drag and drop effect using RX, with support for clipping so you can’t drag the outside the parent container.
Here’s the basic HTML for the demo and with some simple CSS how it looks:
As you can see, this example uses jQuery and included in the RXJS package is a rx.jQuery.js file which contains a number of extension methods to use with jQuery such as the toObservable function which returns a stream of observable values. If this sounds unfamiliar to you I strongly recommend you to read through the first couple of articles by Matthew Podwysocki I linked above.
On line 23, I’m created a composite event stream by pairing mouse move events with their subsequent mouse move event to work out the change in the X and Y direction. To visualise the two event streams and the resultant mouseMoves stream:
Then on line 36, I’ve subscribed an event handler for values pushed down to us through the mouseMoves stream. This event handler applies the X and Y changes to the <div> element’s left and top offset but caps them so that it can only be moved inside its container.
I used jQuery to demonstrate RXJS’s extension functions for jQuery but you don’t need jQuery in order to use RXJS, in the rx.html.js script file there is a very useful Rx.Observable.FromHTMLEvent function which lets you get an observable stream of events from any HTML events including IE-specific events such as ‘oncut’.