As we just released the Reactive Extensions for Javascript I thought it would be nice to dig a bit deeper in what the sample that ships with the download is all about.
For those who haven’t downloaded the bits yet, or haven’t gotten the time to play with the sample, I’ve embedded it right here.
So let's dig into the details of this sample.
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script><script src="rx.js" type="text/javascript"></script>
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++){ var s = $(document.createElement("span")); s.html(text.charAt(i)); s.css({ position: "absolute"}); s.appendTo(container);}
var text = "time flies like an arrow";var container = $("#container");for (var i = 0; i < text.length; i++){ var s = $(document.createElement("span")); s.html(text.charAt(i)); s.css({ position: "absolute"}); s.appendTo(container);
mouseMove.Subscribe(function(mouseEvent) { s.css({ top: mouseEvent.offsetY + "px", left: mouseEvent.offsetX + "px" }); });}
We can change this behavior by wrapping the body of the for loop in a function, which will change the scoping of the variables:
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.Subscribe(function(mouseEvent) { s.css({ top: mouseEvent.offsetY + "px", left: mouseEvent.offsetX + "px" }); }); })(i);}
left: mouseEvent.clientX + i * 10 + 15 +
Delay is defined on the Rx.Observable prototype and it takes a dueTime as an argument, it returns a new observable collection. When a notification arrives on the original observable collection, the operator will delay that notification for the time specified by dueTime and after that time will fire out the notification on the resulting observable collection.
Rx is a fluent api so we can insert the call to Delay directly in one of our expressions dealing with an observable collection:
mouseMove.Delay(i * 100).Subscribe(
Leading to the final version:
mouseMove.Delay(i * 100).Subscribe(function(mouseEvent) { s.css({ top: mouseEvent.offsetY + "px", left: mouseEvent.offsetX mouseEvent.clientX + i * 10 + 15 + "px" }); }); })(i);}
You can download Rx for JavaScript on Rx's devlab page. Questions can be asked on the Rx forum. If you're looking for more samples about Rx for JavaScript, I can recommend Matthew Podwysocki's blog.
Also don't forget to follow @jvgogh and #RxJS on twitter