Rx - for beginners (part 12): RxJs
this post is the 11th in a series of posts about the new Reactive Framework (Rx).
the series TOC can found here.
in this post we will focus on Rx for JavaScript.
the recently the Rx team release JavaScript library that capable to
get observable stream from events.
for example the syntax for mouse move event will be:
- var mouseMove = Rx.Observable.FromJQueryEvent($(document), "mousemove");
all you have to do in order of using this library is to rx.js which is less than 7Kb (GZipped).
- <script src="rx.js" type="text/javascript"></script>
you can download the installation from here.
the installation include sample code that demonstrate old good JavaScript trick of
attacking sting tail to the mouse move event.
to see the effect move the mouse on the gray panel.
Rx on javascriptRx on javascriptRx on javascript
the full code for this trick is:
Code Snippet
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head>
- <title>Rx for JavaScript Rocks!</title>
- <script src="http://code.jquery.com/jquery-latest.js"></script>
- <script src="rx.js" type="text/javascript"></script>
- <script type="text/javascript">
- $(document).ready(function()
- {
- var mouseMove = Rx.Observable.FromJQueryEvent($(document), "mousemove");
-
- var text = "time flies like an arrow";
- var container = $("#container");
- for (var i = 0; i < text.length; i++)
- {
- (function(i)
- {
- var s = $(document.createElement("span"));
- s.html(text.charAt(i));
- s.css({ position: "absolute" });
- s.appendTo(container);
-
- mouseMove.Delay(i * 100).Subscribe(function(mouseEvent)
- {
- s.css({ top: mouseEvent.clientY + "px",
- left: mouseEvent.clientX + i * 10 + 15 + "px"});
-
- });
- })(i);
- }
- });
- </script>
- </head>
-
- <body style="font-family: Consolas, monospace; overflow: hidden">
- <div id="container"></div>
- </body>
- </html>
line 9, getting observable stream.
line 13, iterate for each of the character of the text.
lines 22-27, subscribe to the event stream (for each of the character).
Summary
the Rx framework is now available for web developers.
Learn More