Archive for the ‘Javascript’ tag
node.js: anatomy of a net connection
Been looking into the awesome node.js project, “evented I/O” server-side Javascript running on V8. I got introduced to node.js while attending a Bayjax meeting back in May dubbed Cinco de Node.js with node.js’ creator Ryan Dahl presenting (video).
My little side project (more on that later) involved delving into the internals of the node.js Javascript library and figuring out how a network connection was made. It turns out to be quite nontrivial with the myriad async calls and network socket handshaking. I started to document the connection process and wanted to share it. Perhaps others will find it useful also.
A typical client-server connection code can found in the node.js test harness, eg, test-http-1.0. Create a server:
var server = http.createServer(function (req, res) { res.writeHead(200, {"Content-Type": "text/plain"}); res.end("hello world\n"); }) server.listen(PORT);
and the client:
var c = net.createConnection(80); c.setEncoding("utf8"); c.addListener("connect", function () { c.write( "GET / HTTP/1.0\n\n" ); }); c.addListener("data", function (chunk) { console.log(chunk); }); c.addListener("end", function () { c.end(); server.close(); });
The server goes through the regular socket(), bind(), listen() routine. It then kicks off its readWatcher which listens() for any connections. Once a connect request comes in, it creates a peer socket and pairs it to the incoming connection. It sets the peer’s socket error state to zero (0), which tells the peer that the connection was successful. Finally, it kicks off connectionListener(), which waits for incoming data. The server logic is shown in this diagram: (click for full image)
Meanwhile, back at the client, net.createConnection() calls the doConnect() routine which calls socket connect(). If a server is found at the address:port, the client’s socket state is set to ‘connect in progress’ (EINPROGRESS), and the socket is made writable. This triggers the client’s writeWatcher, which checks the client’s socket error state for zero (connected). When the socket is connected, the client’s readWatcher is kicked off which listens for response data, and it emits the ‘connect’ event, indicating the client is ready to make a request. The client logic is show in the following diagram (click for full image):
The exact sequence of events and calls may change as node.js is under fast-paced development (the diagrams correspond to roughly v0.1.96). But it should give a good overview of the sequence of events and relation to the callbacks.
More node.js goodness will be coming.
_xiterator: an expression iterator for Underscore
Underscore.js is an excellent, compact Javascript library extending the language with useful tools. Most of the utils are drawn from Prototype and/or been inspired by languages such as Ruby. Underscore reverts to native code where it is supported.
A hand-full of so-called Collection functions which operate on arrays & objects, such as _any(), _all(), _map(), and _detect(), take an iterator function as an argument:
if ( _.any([1,2,3], function iterator(value){ return ! _.isNumber(value); })) { // ... }
_.isNumber() is one of a dozen or so type checking routines provided by Underscore, in addition to, _isString(), _isFunction(), _isArray(), and others.
Often times the iterator is a simple type-checking, like above, or some sort of expression that needs to be evaluated. So why not just enter the expression:
if (_.any([1,2,3], "!isNumber")) { // ... }
This is what _xiterator, an add-on for Underscore, provides. It is simply the meat of the iterator in a compact semantic.
Let’s throw in some range checking:
if (_.any([1,2,3], function iterator(value){ return ! _.isNumber(value) || value < 0 || value > 10; })){ // ... }
can be replaced by:
if (_.any([1,2,3], "!isNumber || < 0 || > 10")){ // .... }
Expression iterators
The expression is composed of valid Javascript code. In the case of relational operators (<, <=, ==, etc.) the left operand is implied to be the value of the iterator. The expression is evaluated in global scope.
Any of the Underscore _.isXXX type-checking routines can be used without the argument (the _. part is implied). In addition, three new routines are added: isBlank, isOdd, isEven.
Parenthetical expressions are fully supported:
_.any([1,2,3], "(isNumber && > 0) || (isString && !isBlank)");
Validating functions:
function checkZip(value) {...} _.any(zips, "!isBlank && checkZip(__value) "); // __value is the placeholder
In addition to __value, __key and __list placeholder variables, corresponding to the formal arguments of the iterator, are available.
How about a regular expression:
_.all([1,2,3], /\d+/); // either as string or RegExp object
Of course, functions are still supported and will work as before.
Accessing original methods
Since the expression string needs to be parsed, runtime performance will be affected. Performance sensitive applications involving huge sets should use the original routine.
The original routines can be explicitly accessed by passing no argument, eg.
var originalAny = _.any(); originalAny(veryLargeSet, function(){...});
Or more compactly,
_.any()(veryLargeSet, function(){...});
Expressions cannot be used on original methods:
originalAny(veryLargeSet, 'isNumber'); //Â => raises exception
The code
Details, code, and examples (including test suite) are on Github.  Released under MIT license.
Update: Just came across Functional.js. Above technique is not too dissimilar to its string `lambda` functionality.
Introducing touch-enabled spinControl
Hot on the heels of sliderControl comes its close cousin, the spinControl. Whereas in the sliderControl, the thumb widget is moved across a fixed set of values to select the desired input, in the spinControl the whole set is movable. This allows for larger set of data that can fit on the visible screen.
All the features of sliderControl are supported (kinetics, bounce, snap, toggle, events handlers, etc.). Additionally, a new alignToEdge option allows the scroll area to align to the left and right edge of the viewport instead of its center.
For gory details, demo and download, see spinControl page.
Bonus
Also included is a spinToggle class that mimic’s iPhone’s toggle switch, complete with slide action.
Emulating iPhone’s slide-to-unlock
The touch-enabled sliderControl covered earlier is an easy UI widget to select a value from a set or a range of numbers. It can be easily modified to function as a slide-to-unlock contorl that you see on the iPhone. Enter the slideToAction control:
mySlider6 = new slideToAction('#slider6', ['slide to unlock'], { onchange: function(){ alert('unlocked'); // some useful action! } });
Markup:
<div id="slider6" class="slider"></div>
When the thumnail is moved all the way to the end, the onchange handler gets called. Simple. slideToAction inherits all of sliderControl’s kenetics and emulates the spotlight effect of iPhone’s control.
slideToAction is included as part of sliderControl. See item #6 ‘single value slider’ on the demo page.
(The thumbnail looks better on the iPhone browser!)
The spotlight effect of the label text is achieved using -webkit-mask-* CSS attribute and animating the -webkit-mask-position property. Here’s the CSS:
.sliderAction .sliderLabel { font-size:18px; font-weight:normal; text-shadow:none; color: #fff; -webkit-mask-image: -webkit-gradient(linear, 35% top, 65% top, from(rgba(0,0,0,.20)), color-stop(.5,rgba(0,0,0,1)), to(rgba(0,0,0,.20))); -webkit-mask-size: 50%; -webkit-mask-repeat: none; -webkit-animation-name: spotlight; -webkit-animation-timing-function: linear; -webkit-animation-duration: 1500ms; -webkit-animation-iteration-count: infinite; }
using the animation keyframes:
@-webkit-keyframes spotlight { from {-webkit-mask-position: 0;} to {-webkit-mask-position: 100%;} }
The -webkit-mask-position property is animated on desktop Safari 4.x and Chrome 4.x. It isn’t supported on iPhone OS 3.1.2 browser… but hopefully it will under 3.2.
Update: (11 March 2010)
New version 0.1a has an updated slideToAction() that looks more like the real thing. Here’s a screenshot.
Seems like SDK developers have been trying to get this feature implemented as well. See here and here.
Introducing a touch-enabled slider control
I needed a touch-enabled slider input control for a project I was working on. Unfortunately there was no good existing solution, so I rolled my own.
Features:
- kinetic snap to value
- optimized CSS animation
- full range of slider values supported
- customizable with extensive options
- fully programmable
- event callbacks
- adjusts on orientation change
- works on desktop webkit browsers (for testing)
- theme to taste!
See sliderControl page for details.
★ More on PastryKit
Daring Fireball
Lastly, there’s the question of how concerned Apple is, strategically, that a robust web app API and market would take away from the App Store. And if so, are they worried about the money? I’d guess probably not. I don’t think Apple’s 30 percent cut of App Store revenue is anything to sneeze at, and it’s growing fast. But there’s no question that the App Store exists to sell iPhones and iPod Touches, not the other way around.
Lawnchair – client side JSON document store
Sorta like a couch except smaller and outside, also, a client side JSON document store. Perfect for webkit mobile apps that need a lightweight, simple and elegant persistence solution.