JS101: Inheritance

28 May 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner
JS101 is a tutorial series aimed at beginners. Each post is a bite-sized chunk aimed to elucidate JavaScript fundamentals. To read previous posts, view the js101 tag.

Inheritance Chains and Constructors

As we saw last week, JavaScript objects have a prototype property, which is designed to facilitate inheritance. An object’s prototype property can be set to an instance of another object to create an inheritance chain:

function Shape(name) {
  this.x = 0;
  this.y = 0;
  this.name = name;
  console.log('Shape constructor called');
}

Shape.prototype = {
  move: function(x, y) {
    this.x += x;
    this.y += y;
  },

  toString: function() {
    return 'name: ' + this.name + ', at x: ' + this.x + ', y:' + this.y;
  }
};

// Rectangle
function Rectangle(name) {
  this.name = name;
  console.log('Rectangle constructor called');
}

Rectangle.prototype = new Shape();

var rect = new Rectangle('Player 1');
rect.move(1, 1);
console.log(rect.toString());
console.log(rect instanceof Rectangle);

Running this will display the following output:

Shape constructor called
Rectangle constructor called
name: Player 1, at x: 1, y:1
true

Notice that both the Shape and Rectangle constructors are called. This is because of the line Rectangle.prototype = new Shape(); – the parent object’s constructor isn’t actually automatically called as a result of new Rectangle(). This is why I’ve duplicated the this.name = name line in both constructors.

Also notice that rect.move and rect.toString call the methods from Shape.prototype. When the interpreter checks for a property, it will examine the current object for it. If no such property is found, the prototype for the object is checked, and so on. This is the prototype chain:

First the object mentioned directly is examined for such a property; if that object contains the named property, that is the property to which the reference refers; if that object does not contain the named property, the prototype for that object is examined next; and so on.

Annotated ECMAScript 5.1

Calling Parent Methods

If we wanted Rectangle to have a different move method, but reuse the original in Shape, then it’s entirely possible to do so using Function.prototype.apply:

Rectangle.prototype.move = function(x, y) {
  console.log('Super method called');
  Shape.prototype.move.apply(this, arguments);
};

Even though Shape.prototype.move.apply looks complicated, it’s actually very simple if we break it down:

  1. We want to call the move method from Shape
  2. This method is stored in Shape.prototype.move
  3. Since this is a Function, there are several methods available to us (functions are objects!)
  4. The apply method in particular allows us to call the function without creating a new instance
  5. It also allows us to provide our own value for this, and an array of arguments

The arguments object is created by the interpreter when a function is executed. The this object is a whole other story – so far I’ve been assuming you have intuitively understood what it is, but we’ll look at it in more detail in the next part.

References

Ender Roundup: tablesort.js, Moment.js, jwerty, SelectNav.js, ender-events, ender-assert, Categorizr.js, Arbiter

You can send in your Ender-related projects for review through our contact form or @dailyjs. Be sure to also update the Ender package list page on the Ender wiki.

tablesort.js

tablesort.js (GitHub: tristen/tablesort, npm / Ender: tablesort) by Tristen Brown is a dependency-free sorting library for HTML tables. tablesort.js can be invoked stand-alone via new Tablesort(document.getElementById('table-id')) or $('#table-id').tablesort() method from within Ender.

Olivier Vaillancourt has written a small review of tablesort.js for use in Ender on Twitter Bootstrap tables.

Moment.js

Moment.js (GitHub: timrwood/moment, npm / Ender: moment) by Tim Wood is small, yet very comprehensive date and time handling library.

Moment.js

Moment.js was mentioned last year on DailyJS but it now has a simple Ender bridge allowing you to pack it neatly into Ender builds for use via $.ender(). Plus, it’s an absolutely fantastic library for anything date/time related so it’s worth mentioning again. Be sure to scan the docs to see just how much this library can do.

$.moment().add('hours', 1).fromNow(); // "1 hour ago"

// manipulate
$.moment().add('days', 7).subtract('months', 1).year(2009).hours(0).minutes(0).seconds(0);

// parse dates in different formats
var day = $.moment("12-25-1995", "MM-DD-YYYY");

var a = $.moment([2010, 1, 14, 15, 25, 50, 125]);
a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
a.format("ddd, hA"); // "Sun, 3PM"

// operate on different 'moment' objects
var a = $.moment([2007, 0]);
var b = $.moment([2008, 5]);
a.diff(b, 'years'); // 1
a.diff(b, 'years', true); // 1.5

The project maintainers also follow a rigorous release methodology, making great use of git branches, something that is not often found on smaller open source libraries.

jwerty

jwerty (GitHub: keithamus/jwerty, Licence: MIT, npm / Ender: jwerty) by Keith Cirkel is a small keyboard event handling library which can bind, fire and assert key combination strings against elements and events.

$.key('ctrl+shift+P', function () { [...] });
$.key('⌃+⇧+P', function () { [...] });

// specify optional keys
$.key('⌃+⇧+P/⌘+⇧+P', function () { [...] });

// key sequences
$.key('↑,↑,↓,↓,←,→,←,→,B,A,↩', function () { [...] });

// pass in a selector to bind a shortcut local to that element
$.key('⌃+⇧+P/⌘+⇧+P', function () { [...] }, 'input.email', '#myForm');

// use `$.event` as a decorator, to bind events your own way
$('#myinput').bind('keydown', $.keyEvent('⌃+⇧+P/⌘+⇧+P', function () { [...] }));

// use `$.isKey` to check a key combo against a keyboard event
function (event) {
    if ( $.isKey('⌃+⇧+P', event) ) { [...] }
}

// use `$.fireKey` to send keyboard events to other places
$.fireKey('enter', 'input:first-child', '#myForm');

SelectNav.js

SelectNav.js (GitHub: lukaszfiszer/selectnav.js, npm / Ender: selectnav.js) by Lukasz Fiszer is a small library that will convert your website’s navigation into a <select> menu. Used together with media queries it helps you to create a space saving, responsive navigation for small screen devices. SelectNav.js is inspired by TinyNav.js for jQuery.

ender-events and ender-assert

ender-events (GitHub: amccollum/ender-events, Licence: MIT, npm / Ender: ender-events) and ender-assert (GitHub: amccollum/ender-assert, Licence: MIT, npm / Ender: ender-assert) are two packages by Andrew McCollum, previously bundled in his node-compat library. ender-events gives you an implementation of the NodeJS EventEmitter class in your browser, while ender-assert gives you a browser version of the NodeJS assert module.

Andrew also has a tiny extension to Bonzo, the DOM utility included in Ender’s starter pack (The Jeesh), named ender-remove that simply triggers a ‘remove’ event when nodes are removed from the DOM. Which can be helpful for performing clean-up actions.

Categorizr.js

Categorizr.js (GitHub: Skookum/categorizr.js, Licence: MIT, npm / Ender: categorizr) by Dustan Kasten is a JavaScript port of the Categorizr PHP script by Brett Jankord.

Categorizr gives you $.isDesktop() $.isTablet() $.isTV() $.isMobile() methods to determine the current device.

Arbiter

Arbiter (GitHub: iamdustan/arbiter, Licence: MIT, npm / Ender: arbiter) also by Dustan Kasten is a tiny library for managing the HTML5 history interface via pushState(), using AJAX requests to load new content upon request.

Windows and Node: Writing Portable Code

24 May 2012 | By Alex Young | Comments | Tags node tutorials windows windows-and-node

I’ve been surveying popular Node modules and the nodejs Google Group to find common portability issues people have found when testing modules in Windows.

For the most part, Node code seems very portable – there are only a few problem areas that seem to crop up frequently. Let’s take a look at these problems and the solutions so we can write code that runs everywhere.

Platform-Specific Code

Despite Node code’s inherent portability, there are times when platform-specific code is required. This is dealt with in Node’s core modules like this:

var isWindows = process.platform === 'win32';

if (isWindows) {
  // Windows-specific code
}

This example is based on path.js.

For more detailed information on the operating system, the os module can come in handy.

Nodes OS module in Windows

File System

Windows can actually accept backslashes or forward slashes as a path separator. This means you don’t need to change all of your require calls to use different slashes; most things should just work. There are a few cases where we need to be careful, however, particularly if a path name is absolute or it’s going to be displayed somewhere.

One common issue I’ve found is where the developer has made certain assumptions about the structure of absolute paths. In a commit to Express, Fixed absolute path checking on windows, we can see where the authors have adapted a method called isAbsolute to support Windows:

exports.isAbsolute = function(path){
  if ('/' == path[0]) return true;
  if (':' == path[1] && '\\' == path[2]) return true;
};

Isaac Schlueter recommends using path.resolve to make relative paths absolute in a cross-platform way.

When dealing with fragments of paths, using path.join will automatically insert the correct slash based on platform. For example, the Windows version will insert backslashes:

var joined = paths.join('\\');

Notice that JavaScript strings require two backslashes because one acts as an escape, so when working with Windows path names don’t be surprised if there are lot of double slashes.

Another big source of Windows issues is fs.watch. This module is routinely used by programs that watch for file system changes. Node’s documentation makes it clear that the API isn’t portable, so the slower but more compatible fs.watchFile can be used instead.

In this patch for the Derby web framework, we can see where the developers opted to branch based on process.platform to use fs.watchFile in Windows, but fs.watch elsewhere.

Text Interfaces

Be aware that not everybody has a super-fancy UTF-8 terminal that supports colours. Certain programs depend on text output, but people may have trouble seeing it correctly if your program relies on symbols their terminal or font doesn’t support.

Mocha is a good example of such a program, and in the issue Ability to configure passed/failed checkmarks for the spec reporter, we can see where someone has struggled to read the output with cmd.exe.

Environment

Assuming certain environmental variables will exist (or mean the same thing) on every platform is a good way to create portability headaches.

James Halliday’s Browserify had its fair share of Windows issues, which was problematic due to several other popular modules depending on it.

This commit to Browserify demonstrates a fix Christopher Bennage submitted that replaces calls to process.env.HOME with the following:

var home = (process.env.HOME || process.env.USERPROFILE);

I tried this in Windows 7 and found process.env.HOME wasn’t set, but process.env.USERPROFILE worked as expected.

Sockets

Node’s TCP sockets are portable, but Unix domain sockets are not. However, Windows has named pipes. The following code is almost exactly the same as the Unix equivalent, it just has a different path to the named pipe:

var net = require('net');

net.createServer(function(socket) {
  console.log('Connected');
}).listen('\\\\.\\pipe\\named-pipe-test');

Notice the escaped backslashes – forgetting to insert them here will raise a confusing EACCESS error. In node/test/common.js, there’s a branch based on platform to set the name of the pipe so it works in Windows and Unix:

if (process.platform === 'win32') {
  exports.PIPE = '\\\\.\\pipe\\libuv-test';
} else {
  exports.PIPE = exports.tmpDir + '/test.sock';
}

References

Node Roundup: Uptime, mmmagic, nodeflix, opt

23 May 2012 | By Alex Young | Comments | Tags node modules apps cli express unix
You can send in your Node projects for review through our contact form or @dailyjs.

Uptime

Uptime screenshot

Uptime (GitHub: fzaninotto / uptime, License: MIT, npm: node-uptime) by Francois Zaninotto is an Express app for remote server monitoring. It’s built with Mongoose, Bootstrap, ejs, Socket.IO, and jQuery.

To use the app, a YAML configuration file must be created for the sites you want to monitor. It seems like JSON would have been a more natural choice, but it’s pretty easy to get started and there are examples in the documentation.

I’m always looking for open source Express applications, so keep them coming!

mmmagic

mmmagic (License: MIT, npm: mmmagic) by Brian White is a Node addon for libmagic, as used by the file) command. It’s asynchronous, and can provide the MIME type for a file (as well as other metadata):

var mmm = require('mmmagic')
  , Magic = mmm.Magic;

var magic = new Magic(mmm.MAGIC_MIME_TYPE);
magic.detectFile('/usr/bin/env', function(err, result) {
  if (err) throw err;
  console.log(result);
});

It’s currently built with node-waf (rather than gyp), but the author has included a Windows binary.

Nodeflix

Nodeflix (License: MIT, npm: nodeflix) by Johnathan Leppert is a Netflix API client:

n.get('/catalog/people', { term: 'DeNiro' }, function(data) {
    console.log(data);
});

I’ve noticed quite a few Node media-related modules cropping up, and with the continually improving Windows support it seems like Node is becoming a strong platform for home theatre-related application development. Is there a Node XBMC alternative yet?

opt

opt (License: New BSD License, npm: opt) by R. S. Doiel is an options parser that can also load configuration files. It can generate usage based on the supplied parameters, but has a slightly different API to the other option parsing modules I’ve looked at – callbacks are tied to each option instead of working with a parsed set of options:

#!/usr/bin/env node
var opt = require('opt')
  , args;

function test(param) {
  if (param) {
    console.log('--test parameter:', param);
  } else {
    console.log('No parameter supplied to --test');
  }
}

opt.setup('Simple test script.');
opt.set(['-h', '--help'], opt.usage, 'Show help');
opt.set(['-t', '--test'], test, 'Run test');

opt.parse(process.argv);

This is quite different to how Commander.js works, for example.

jQuery Roundup: jQuery UI 1.9 Milestone 8, Chico UI, Complexify

22 May 2012 | By Alex Young | Comments | Tags jquery jqueryui libraries security
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

jQuery UI 1.9 Milestone 8

jQuery UI 1.9 Milestone 8 has been released. The major change in this release is a redesign of the Position utility script.

There are also bug fixes and accessibility improvements.

Chico UI

Chico banner

Chico UI (GitHub: mercadolibre / chico, License: MIT) from MercadoLibre is a set of UI widgets built with jQuery. The project includes demos with documentation for each widget, I’ve selected a few interesting ones here but there are a lot more:

There’s also Chico Mesh for creating CSS column-based layouts, and some tutorials on Chico.

The mix of JavaScript widgets and reusable layout CSS reminds me of a combination of jQuery UI and Bootstrap. I haven’t seen Chico before, but the authors have been committing frequently to the GitHub project over the last two years, so at this point it seems relatively mature.

Complexify

Complexify

Complexify (GitHub: danpalmer / jquery.complexify.js, License: WTFPL v2) by Dan Palmer is a password complexity checker. It’s used like this:

$('#password').complexify({ minimumChars: 8 }, function(valid, complexity) {
  // valid: Password is the right length
  // complexity: Password complexity rated as a percentage
});

The algorithm Dan’s written to rate complexity is based on blocks of Unicode:

The rationale behind this is that in an attacker were wanting to include Japanese passwords in his attack, he/she may choose to include the Hiragana set in his/her attack, but not the Katakana set. Complexify divides Unicode into 94 appropriately grouped sets.

The main driver behind the algorithm is to try to distinguish between complex passwords, and passwords that have the illusion of complexity due to security policies.

JS101: Prototypes

21 May 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner
JS101 is a tutorial series aimed at beginners. Each post is a bite-sized chunk aimed to elucidate JavaScript fundamentals. To read previous posts, view the js101 tag.

After spending years studying object oriented programming, adapting to JavaScript can be frustrating. In particular, the lack of a class keyword is a source of confusion. However, JavaScript’s design needn’t be a hindrance – mastering its prototype-based inheritance will improve your understanding of the language.

The first thing to realise is there should be a distinction between object-oriented programming and class-oriented. JavaScript gives us the tools we need to do most of the things languages with classes can do – we just need to learn how to use it properly.

Let’s take a brief look at the prototype property to see how it can deepen our knowledge of JavaScript.

The prototype Property

The prototype property is an internal property, and it’s designed to be used to implement inheritance. What we mean by “inheritance” here is a specific form of inheritance. Because both state and methods are carried by objects, then we can say that structure, behaviour, and state are all inherited (ES5: Objects). This is in contrast to class-based languages, where state is carried by instances and methods are carried by classes.

A constructor is a function that has a property named prototype:

function Animal() {
}

console.log(Animal.prototype);

This displays {} – the Animal object has a prototype property, but there’s nothing user-defined in it yet. We’re free to add values and methods as we please:

function Animal() {
}

Animal.prototype.type = 'Unknown';
Animal.prototype.weight = 0;
Animal.prototype.weightUnits = 'kg';

Animal.prototype.toString = function() {
  return this.type + ', ' + this.weight + this.weightUnits;
};

var molly = new Animal();
molly.type = 'Dog';
molly.weight = 28;

console.log(molly.toString());

This would display “Dog, 28kg”. We can group these assignments together by using an object literal:

function Animal() {
}

Animal.prototype = {
  type: 'Unknown',
  weight: 0,
  weightUnits: 'kg',

  toString: function() {
    return this.type + ', ' + this.weight + this.weightUnits;
  }
};

This shouldn’t look too different from the classes you might be more familiar with.

Dynamic Prototypes

Properties can be added to objects dynamically, simply by assigning values:

var molly = new Animal()
  , harley = new Animal();

molly.type = 'Dog';
molly.weight = 28;

harley.type = 'Dog';
harley.weight = 38;
harley.name = 'Harley';

console.log(molly);
console.log(harley);

// { type: 'Dog', weight: 28 }
// { type: 'Dog', weight: 38, name: 'Harley' }

Adding the name property here only affects that instance. However, the constructor’s prototype can be changed, and this will affect objects made with that prototype:

Animal.prototype.weightUnits = 'oz';

console.log(molly.toString())
// Now displays 'Dog, 28oz'

This is why people boast that their libraries don’t touch native prototypes, or only do so safely – it’s entirely possible to change the expected built-in functionality of objects like String to do unsafe things:

String.prototype.match = function() {
  return true;
};

console.log('alex'.match(/1234/));

This returns true, so I’ve now succeeded in breaking a fundamental method that many JavaScript programs rely on.

Modifying native prototypes isn’t always bad; people use it for useful things like patching support for more modern versions of ECMAScript in older browsers.

What happens if we replace the prototype property?

var molly = new Animal()
  , harley;

molly.type = 'Dog';
molly.weight = 28;

Animal.prototype = {
  toString: function() {
    return '...';
  }
};

harley = new Animal;
harley.type = 'Dog';
harley.weight = 38;

console.log(molly.toString());
console.log(harley.toString());

// Dog, 28kg
// ...

Despite the fact changing a prototype affects all of the instances, replacing a constructor’s prototype entirely does not affect older instances. Why? Well, instances have a reference to the prototype rather than a discrete copy. Think of it like this: each instance created by the new keyword is connected to the original prototype.

Next Week

In the spirit of keeping this post bite-sized, I’ll finish here. Next week we’ll look at prototype chains and inheritance in more detail.

References

Page, testr.js, screenfull.js

18 May 2012 | By Alex Young | Comments | Tags testing fullscreen routing

Page

If I had to place a bet on the most activity by one person on GitHub, I’d bet on TJ Holowaychuk. His latest project is Page.js (GitHub: visionmedia / page.js, npm: page), which is a client-side router. The routing syntax works like Express, so variables are denoted by :name, and the * route can be used to catch 404s. In this case, 404 is open to interpretation.

page('/', index)
page('/user/:user', show)
page('/user/:user/edit', edit)
page('/user/:user/album', album)
page('/user/:user/album/sort', sort)
page('\*', notfound)
page()

It’s actually a very lightweight project, based around pushState, but it includes detailed comments and Mocha tests.

testr.js

testr.js (License: MIT) by Matt Fysh is for unit testing RequireJS modules. Use it with your favourite test framework to test both stubbed and script-loaded dependencies:

testr('path/to/module', stubs);
testr('path/to/module', useExternal);
testr('path/to/module', stubs, useExternal);

The author has written some projects that use testr.js – asq and after both use it with Jasmine.

screenfull.js

screenfull.js (GitHub: sindresorhus / screenfull.js, License: MIT) by Sindre Sorhus is another wrapper around the Fullscreen API. The semantics are similar to the specification, but a lot simpler – the README has a comparison with “vanilla” JavaScript which is several lines of code. Using screenfull.js, only screenfull.request() is required to trigger fullscreen mode.

The library can do other things as well: a single element can be fullscreened, or events can be used to detect a change to fullscreen mode.

Windows and Node: Addons

17 May 2012 | By Alex Young | Comments | Tags node tutorials windows addons gyp windows-and-node

In this article we’re going to look at addons. If you’re a Node developer working in Windows then this article should give you enough background to at least understand the basic issues surrounding addons, and install them using npm.

Addons are something Unix-based Node developers generally have little trouble with. However, the history of addon support in Windows has been a little bit turbulent. We’ve seen various solutions come and go – most notably node-waf and Cygwin – but the community has now settled on node-gyp by Nathan Rajlich.

Hint: Addons use C or C++ libraries. Node modules may include both addons and JavaScript code.

Isaac Schlueter summarised it in this comment:

Node-waf doesn’t work on Windows. We’re working on a solution that will make it easier to get a build toolchain in Windows based on node-gyp. Many packages will have to be updated to use this instead, so we’re trying to make it as easy a transition as possible.

Installing a Module with Native Code

The fibers module uses node-gyp for building its native components. However, the module’s author, Marcel Laverdet, has packaged it in an extremely effective way. Rather than force everybody to build the module, he’s included binaries in the npm package. These are not present in the GitHub repository, but are available through npm. This includes both 32 and 64 bit versions.

node-fibers installation in Windows

Therefore, simply running npm install fibers should result in a working module in Windows. The compressed archive on npm actually includes Linux, Mac OS, and Windows binaries, for example: bin/win32-ia32/fibers.node.

Building a Module in Windows

As an exercise, let’s build the fibers module. I picked this one because I already know it works – although there are other modules built with node-gyp, they don’t all build correctly in Windows yet.

Building the module requires a few dependencies:

  • A global installation of node-gyp
  • Python 2.7
  • Microsoft Visual Studio (“Express” is free)

Installing node-gyp

The node-gyp module is easy to install, but just make sure it’s installed globally so it’ll be in your %PATH%:

npm install -g node-gyp

Installing Python

GYP, or Generate Your Projects, is a build system that uses Python. GypUserDocumentation covers the basics, but from our perspective we just need a working version of Python 2.7.x to use it.

I installed Python 2.7.3 using the MSI installer.

Installing Microsoft Visual Studio

Microsoft provides a free edition of Visual Studio called Visual Studio 2010 Express. I downloaded the ISO and extracted the ISO using 7-Zip. It’s 694 MB, so you might want to brew a suitable hot drink while it’s downloading.

Installing Visual C++

Fortunately, Microsoft provide this suite of tools and compilers for free with no user registration.

Running Microsofts IDE

Building the Module

I downloaded the latest zip of node-fibers from GitHub, opened Command Prompt, changed directory to the path of the extracted zip, then ran the following:

set PATH=%PATH%;C:\Python27
node-gyp configure
node-gyp build

Building the fibers module

Once that was done I ran npm test, and the tests all passed. I found it quite satisfying to see Microsoft’s compiler actually build something, and although it’s not necessary to build the fibers module this way, there are other modules out there that don’t include binaries in npm.

Conclusion

Hopefully you now appreciate a little bit about how addons are built in Windows. Although previously the situation was confusing, the community is starting to convert modules to build with node-gyp.

I suspect there will be cases where native code can’t be shipped as binaries due to licensing constraints, but it would be encouraging to see more addons include binaries for Windows.

Node Roundup: express-soap2json, cb, ApiServer

16 May 2012 | By Alex Young | Comments | Tags node modules
You can send in your Node projects for review through our contact form or @dailyjs.

express-soap2json

SOAP might not be the most exciting technology to work with, but if you like Node and Express then express-soap2json (License: MIT, npm: express-soap2json) by Tony Sokhon can make it a little bit easier to work with.

By wrapping around a SOAP service, express-soap2json creates a JSON/HTTP proxy. It’s built using the soap module by Vinay Pulim. Tony has included some Mocha tests, and the README has some basic documentation.

An Alternative to Node’s console.time

In A Powerful Alternative to Node’s console.time(), Dmitri Melikyan discusses using his Nodetime profiler in place of console.time and console.timeEnd.

What if you want to know more about what happens in-between, say CPU time or other nested network of file operations in microsecods precision?

cb

cb (License: MIT, npm: cb) by Jeremy Martin is yet another control flow library. Or is it?

Not exactly. There are literally hundreds of libraries available for easing some of the pains associated with the continuation passing style, and most of them do a pretty good job at this.

Rather than compete with these libraries, cb() focuses on a much narrower range of problems, and is intended to be complementary to your control flow library (or lack thereof) of choice.

It features timeout and error handling with a chainable API, so the following is possible:

var cb = require('cb')
  , fs = require('fs');

fs.readFile(
  '/usr/share/dict/words'
, 'utf8'
, cb(console.log)
    .error(console.error)
    .timeout(50)
    .once()
);

ApiServer

ApiServer (GitHub: kilianc / node-apiserver, License: MIT, npm: apiserver) by Kilian Ciuffolo is a modular framework that’s a bit like Restify, but can also be used to make Express-style web applications. Kilian has written his own comparisons with Express and Restify, and it’s compatible with Express middleware even though it’s not built with Connect.

The routing module, apiserver-router, features a caching system, and applications are built using objects. These objects are known as modules, and each method is an API endpoint. It works with plain objects and prototype classes – classes are ideal if the module has a state (Kilian’s example passes in a database reference).

The author has also included a Mocha test suite, and the documentation is pretty solid too.

jQuery Roundup: Knob, OmniWindow, bPopup, Pageflipper, Tiler

15 May 2012 | By Alex Young | Comments | Tags jquery touchscreen modal games tiling
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

jQuery Knob

jQuery Knobs

jQuery Knob (GitHub: aterrien / jQuery-Knob, License: MIT/GPL) by Anthony Terrien is a nice and configurable dial widget.

It can be configured to exhibit a wide range of behaviours, from value range entry to an iPod clicker-style “infinite” wheel. The value that is displayed can be directly manipulated as well, and it works with scroll wheels and touchscreens.

OmniWindow

OmniWindow (GitHub: 0x000000 / OmniWindow, License: MIT) by Alexander Rudenko is a fairly small modal window plugin, and the author has attempted to target it at programmers rather than designers.

The documentation is good and covers the main use-cases, and despite stating that the plugin doesn’t support tonnes of options, it includes enough to keep it flexible.

It’s based around events, so it can be used like this:

$('div.modal').omniWindow()
  .trigger('show');

And it allows class names to be overridden, in case you want to integrate it with an existing project:

$('div.another-modal').omniWindow({
  overlay: {
    selector: '.custom-overlay', // don't forget the period symbol! 
    hideClass: 'custom-overlay-closed'
  },
  modal: {
    hideClass: 'custom-modal-closed'
  }
});

bPopup

bPopup by Bjørn Klinggaard is another modal plugin that is simply triggered by calling $('element_to_pop_up').bPopup(). By default it’ll reposition the popup when the browser’s size is changed.

For full details on the available downloads and source code, see 21.04.12: New release, bPopup version 0.7.0.

Pageflipper

Pageflipper (GitHub: wtw-software / pageflipper, License: MIT) from wtw-software uses CSS3 transitions to creative a native-feeling page sliding effect. It looks like something that would appeal to mobile web developers, but will also work with a mouse.

It can also be controlled programmatically:

$('#pageflipper').pageflipper('flipleft')

Tiler

Tiler (GitHub: borbit / tiler, License: MIT) by Serge Borbit is a library for working with infinite grids of tiles. This could be used to display map content, but the author has designed it with games in mind.

It feels more like a standard JavaScript library than a jQuery plugin (although jQuery is a dependency), so using it requires creating an instance of a Tiler object:

var tiler = new Tiler($('#viewport'), {
  tileSize: 200,

  sync: function(options, callback) {
    var tosync = options.tosync;

    tosync.forEach(function(tile) {
      var img = new Image();
      var x = tile[0];
      var y = tile[1];

      img.onload = function() {
        callback([[x, y, $('<img/>').attr('src', img.src)]]);
      };

      img.src = 'image_' + x + '_' + y + '.png';
    });
  }
});

QUnit tests are included.

WebGL Audio, CSS 3D Earth, .Net Classes

14 May 2012 | By Alex Young | Comments | Tags .net libraries webgl graphics audio

WebGL Audio

WebGL Audio with tquery

WebGL experimenter Jerome Etienne has written a short tutorial entitled Sound Visualisation: A Vuemeter in WebGL that demonstrates an impressive, yet simple, WebGL VU meter using the Web Audio API.

To make this work, he’s used his webaudio.js library:

var webaudio = new WebAudio()
  , sound = webaudio.createSound();

sound.load('sound.wav', function(sound) {
  sound.play();
});

This library can be used alongside tquery.

CSS 3D Earth

CSS 3D Earth

CSS 3D Earth by Edan Kwan uses a JavaScript library called PerspectiveTransform to display an interactive model of the Earth using shading and layers.

The original class is by Israel Pastrana, and the experiment is presented with a nice little dat.GUI interface.

.Net JavaScript Classes

Julius Friedman sent in a project he created called Easy JavaScript Generic List Implementation. Since then he’s expanded the scope and uploaded it to CodePlex: .Net JavaScript Implementations.

The list implementation has an API that looks a lot like LINQ:

function Car(make, model) {
  this.make = make;
  this.model = model;
}

var myList = new List();
myList.Add(new Car('Honda', 'Civic'));
myList.Add(new Car('Nissan', 'Sentra'));

var selList = myList.Where('make == 'Honda'').OrderByDescending('model').Distinct();

He’s also working on a Reflection class as well as a pseudo type system.

Fluent, Backbone.xmpp, leFunc, Frisby

11 May 2012 | By Alex Young | Comments | Tags conferences events xmpp backbone.js

Fluent Conference

Fluent

Fluent will be held on May 29-31, in San Francisco. It features several tracks – one covers language issues and includes a session with Brendan Eich. The browser track has talks from employees of social networking favourites Twitter, Facebook, and Twitter, and even Microsoft! There’s also a track for Node sessions, which has speakers from Joyent, Twitter, Groupon, and lots more interesting companies.

“Early price” tickets are on sale until May 15th, and there are several tiers available:

  • All-Access Pass: $1695 (standard price: $1895)
  • Conference Plus Tuesday Workshops: $1295 (standard price: $1495)
  • Conference: $995 (standard price: $1195)
  • Tuesday Workshops: $695 (standard price: $895)

There are discounts for previous O’Reilly conference attendees, company teams, academic staff, non-profits, and students.

Backbone.xmpp

Backbone XMPP Pub-Sub Storage (License: MIT) by Yiorgis Gozadinos is an alternative storage layer for Backbone.js that uses XMPP publish-subscribe.

To use it, set a collection’s sync property to Backbone.xmppSync, and assign an instance of PubSubStorage to the collection’s node property:

var MyCollection = Backbone.Collection.extend({
    sync: Backbone.xmppSync
  , model: MyModel
});

var mycollection = new MyCollection();
mycollection.node = new PubSubStorage('mymodels', connection);

The README has links to full documentation in the form of annotated source.

leFunc

leFunc (License: MIT, npm: leFunc) by John Fawcett is a library that uses type checking to support function overloading in pure JavaScript:

var getItems = leFunc({
  'string'; function(id) {
    // Do something
  },

  'string,object': function(id, options) {
    // Do something else
  },

  'string,object,function': function(id, options, callback) {
    // Do something different
    callback();
  }
});

getItems('123abc'); // Calls the first function
getItems('123abc', { awesome: true }); // Calls the second function
getItems('123abc', { awesome: true }, function(){}); // Calls the third function

At the moment it’ll work with any function signatures that are relatively easy to type check. That means primitive values and objects will work as expected.

Frisby

If you’re testing a lot of REST-based APIs, then Frisby (GitHub: vlucas / frisby, License: BSD, npm: frisby) by Vance Lucas might be what you’re looking for. It’s a REST API testing framework built using Jasmine.

It has a nice and friendly chainable API:

var frisby = require('frisby');

frisby.create('Get Brightbit Twitter feed')
  .get('https://api.twitter.com/1/statuses/user_timeline.json?screen_name=brightbit')
  .expectStatus(200)
  .expectHeaderContains('content-type', 'application/json')
  .expectJSON('0', {
    place: function(val) { expect(val).toMatchOrBeNull("Oklahoma City, OK"); }, // Custom matcher callback
    user: {
      verified: false,
      location: "Oklahoma City, OK",
      url: "http://brightb.it"
    }
  });

The project itself is also fully tested, and comes with API documentation.

Windows and Node: Windows Performance Monitor

10 May 2012 | By Alex Young | Comments | Tags node tutorials windows windows-and-node

It’s time to take a look at a Windows-oriented Node module to see how it works. Before getting messy with C, C++, and all that native module stuff, let’s keep it simple by looking at something that communicates with Windows programs using Node’s streams.

Windows Performance Monitor

Windows Performance Monitor provides extremely detailed logging, featuring a wide array of counters, event trace data, and configuration information. The command-line tool, typeperf.exe can write some of this data to a command window.

For example, typeperf "\Memory\Available bytes" "\processor(_total)\% processor time" will display processor and memory counters. The output looks like this on my computer:

typeperf

Why do I mention this? Well, the Node perfmon module is a wrapper around typeperf that provides a ReadableStream-based API. This is an idiomatic module that demonstrates one way of working with an existing program that comes bundled with Windows.

The perfmon Module

To try it out, open a command window and make a directory:

cd Documents\Code\
mkdir perf-example
cd perf-example

Then install perfmon:

npm install perfmon

Once that’s done, create a JavaScript file that uses the perfmon module to gather some data:

var perfmon = require('perfmon');

perfmon('\\processor(_total)\\% processor time', function(err, data) {
  console.log(data);
});

Running it should display some logging. Press ctrl-c to stop it.

Child Processes

The author has written this by using spawn from the child_process module. In fact, we can execute any executable using this module. Try the following script:

var exec = require('child_process').exec;

exec('echo %PATH%', function(err, stdout, stderr) {
  console.log('PATH:', stdout);
});

The output should look similar to the following screenshot, but it may vary depending on what you’ve got installed:

PATH

The child_process API is exactly the same in Unix, as we saw in the Unix and Node posts.

Portability

Does this mean Node programs are generally portable between Unix and Windows? Well, as you can see in this example, Node’s standard libraries look the same. It’s just the part that touches the operating system that may look different. In this example, the part that reads echo %PATH% would be different in Unix.

We’ll look at other portability issues as this series progresses. For now, your homework is to find more Windows-oriented Node modules and see if you can understand the basic principles at work. The Node documentation will be indispensable for this!

Node Roundup: Video Gallery, Restie, xml-literals, Revised Console

09 May 2012 | By Alex Young | Comments | Tags node modules
You can send in your Node projects for review through our contact form or @dailyjs.

Video Gallery screenshot

Video Gallery (GitHub: meloncholy / node-video-gallery, License: MIT) by Andrew Weeks is a Metro-inspired video gallery written with Express, Jade, and MySQL.

It’s got JSON configuration files, separated routes, and lots of fancy front-end effects. There’s a blog post about it here: Node.js Video Gallery.

Restie

Restie (License: MIT, npm: restie) by Vadim Demedes is an ORM that behaves the same in Node and browsers. Models can be declared then manipulated with the familiar CRUD methods, in a similar fashion to Backbone.js.

var Post = Restie.define('Post');

Post.all(function(err, posts) {
  // GET /posts/
});

 
Post.find_by_id(1, function(err, post) {
  // DELETE /posts/1
  post.remove(function(err) {
    // Post removed
  });
});

The author has included tests that run in both browsers and Node.

xml-literals

xml-literals (npm: xml-literals) by Marcel Laverdet adds Node support for E4X-style XML literals:

var anchor = <a href={href}>Hello</a>;

To mix XML and JavaScript this way, the xml-literals module has to register a file extension first, then files that contain XML literals can be loaded. The following example would make subsequent require calls able to load files that include XML literals:

require('xml-literals').register('js');

// This file contains XML literals
require('my-xml-literal-example');

Revised Console

Revised Console (License: MIT, npm: rconsole) by Thomas Blobaum provides C bindings for syslog and makes the console methods log to syslog. This would log to /var/log/messages (depending on the OS):

require('rconsole')
console.log('hello world')

The author has included an example of using Express’ express.logger to log to syslog, which strikes me as potentially useful for production web apps.

jQuery Roundup: Jewel, Custom Drag and Drop, TouchTouch, BetterExamples.js

08 May 2012 | By Alex Young | Comments | Tags jquery jqueryui touchscreen templating
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

Jewel

Jewel (License: MIT) by Vadim Demedes is an ActiveRecord-inspired DOM query API:

var Post = Jewel.define('#posts', {
  keys: {
    title: 'h1'
  , body: 'p'
  },

  template: function(fields) {
    return '<div class="post"><h1>' + fields.title + '</h1><p>' + fields.body + '</p></div>';
  }
});

// Get all of the posts
var posts = Post.all;

// Create a new post
var post = new Post();
post.title = 'Latest post';
post.body = 'Latest content';
post.save(); // Will be prepended to #posts

It actually combines templating and querying, which seems to work quite well. The author has included some Mocha unit tests, and he’s tested it in everything except IE.

Custom Drag and Drop with Mouse

Roll your own drag-and-drop handling, with help from jQuery UI by Jo Liss is a tutorial that explains how to build customised drag-and-drop interfaces using the jQuery UI Mouse widget.

It’s interesting because I’ve struggled to get Draggable to do what I wanted in more complex or unique situations, and building on Mouse seems to offer the flexibility some projects demand.

TouchTouch

TouchTouch

TouchTouch (GitHub: martinaglv / touchTouch, License: MIT, Demo by Martin Angelov is an image gallery that’s also touchscreen-friendly. It features a responsive interface with CSS3 animations and gestures like swiping.

All it needs is a list of images with links: $('#thumbs a').touchTouch();

BetterExamples.js

BetterExamples.js (GitHub: willemmulder / BetterExamples.js, License: CC BY-SA 3.0) by Willem Mulder is an attempt to make JavaScript code examples more interactive.

It’ll display both logging and errors, next to the code that generated them. This is something that I’d like to succeed because even with great tools like jsFiddle I feel like it’s still difficult to create easy to follow interactive code examples.

JS101: Primitive Values and Objects

07 May 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner

Back to Basics

When people talk to me about DailyJS they often ask for more beginner’s articles. Therefore, we’re starting the JS101 series on DailyJS. These are intended to be short guides on fundamental topics that shouldn’t take more than about 10 minutes to read.

I really believe learning JavaScript comes down to understanding Object, so what better place to start?

Types of Values

In JavaScript, the humble Object underlies many of the language’s strengths. To understand JavaScript objects, let’s consider what types of values we have at our disposal. Take a look at the following example:

var one = 1
  , oneObject = new Number(1);

log(one === oneObject);
log(typeof(one), typeof(oneObject));

I’ve made an interactive version of this example that you can experiment with here: http://jsfiddle.net/uWup3/.

This uses the strict equals operator to compare the value 1 with the object new Number(1), and false is returned. The reason for this is 1 is a primitive value, and is not an object. The number created with new Number is an object, as shown by the value returned by typeof.

There are other primitive values: Undefined, Null, Boolean, Number, and String. Another interesting point relates to Undefined and how it’s a type whose sole value is undefined.

Creating Objects

When working in JavaScript, we mostly concern ourselves with objects. There’s a reason why JSON is so popular and powerful, and it comes down to the flexibility of objects. The main difference between objects and primitive values is objects are clearly comprised of multiple items:

var javascript = {
  influences: ['C', 'Java', 'Scheme']
, designer: 'Brendan Eich'
, created: new Date(1995, 0, 1)
};

The ‘items’ in this object – influences, designer, and created – are known as properties. While it’s difficult to imagine breaking down 10 or true into their constituent parts, this object can easily be broken down. Notice how each value can be a different type – both primitive values and objects can be combined together in an object.

Now consider this:

var javascript = new Object({
  influences: ['C', 'Java', 'Scheme']
, designer: 'Brendan Eich'
, created: new Date(1995, 0, 1)
});

I’ve used new Object to create a new instance. According to the language specification, under Object Initialiser, these forms are equivalent – creating objects with an object literal will return a new object as if new Object() was used. Similarly, the array literal ['C', 'Java', 'Scheme'] will create a new object as if new Array() had been called.

The important thing to notice is the use of a constructor. In this case the constructor is new Object, but there are other built-in constructors. I also sneaked in new Date which creates a Date object.

Constructors

The previous example looks more like a data record than a reusable piece of code. We can make it more reusable by creating a constructor – a function that knows how to initialise a certain flavour of object.

function Language(designer, created, influences) {
  this.designer = designer;
  this.created = created;
  this.influences = influences;
}

var javascript = new Language(
  'Brendan Eich'
, new Date(1995, 0, 1)
, ['C', 'Java', 'Scheme']
);

Now I can make other programming languages:

var c = new Language(
  'Dennis Ritchie'
, new Date(1972, 0, 1)
, ['B', 'ALGOL']
);

The constructor can be accessed using the constructor property, like this: c.constructor. In this case it’ll return Language. Play around with it here: http://jsfiddle.net/zYzER/6/.

In the ES5 specification under Properties of the Object Prototype Object, other properties of objects are mentioned. For example, we also get toString, and some stranger sounding methods like hasOwnProperty.

Next

I’m going to continue this series of back to basics JavaScript each Monday. Think of it as learning JavaScript in bite-sized chunks. Next week I’ll talk about prototypes.

WebGL GTA, 3D Pong, webgl-texture-utils

04 May 2012 | By Alex Young | Comments | Tags webgl graphics libraries games

WebGL GTA

WebGL GTA

WebGL GTA (GitHub: niklasvh / WebGL-GTA, Demo) by Niklas von Hertzen is a WebGL interpretation of the original Grand Theft Auto. It parses the game files and builds maps and game objects, all rendered with glorious WebGL.

There are a few glitches, but it’s amazing how much the author has done while keeping the code relatively easy to follow.

3D Pong

In Augmented Reality 3D Pong by Jerome Etienne, a version of Pong is presented that works using a gesture-based interface. There’s a detailed screencast that explains the code here: Augmented Reality 3D Pong Live Coding Screencast. The actual code is here: jeromeetienne / augmentedgesture.js – take a look at the index.html file to see the non-library part of the project.

webgl-texture-utils

webgl-texture-utils by Brandon Jones (the author of TojiCode) is a set of WebGL texture libraries that can help with loading compressed formats. The file format is inferred by the file extension, but can also be overridden.

It also includes support for the crunch format:

And yes, it does support DDS. The full list of supported formats is currently JPG, PNG, GIF, BMP, DDS, CRN (Crunch), and some TGAs. I don’t actually advocate using TGAs in your WebGL apps, but I had the code available so why not?

Windows and Node: Getting Started

03 May 2012 | By Alex Young | Comments | Tags node tutorials windows windows-and-node

I enjoyed writing the Unix and Node tutorials over the past few months, and I hope they got people thinking about creating Node programs that behave like first-class Unix citizens.

Since last June, when Microsoft partnered with Joyent to port Node to Windows, Node has gone from strength to strength on Microsoft’s ubiquitous OS. I thought it was only fair to give Windows the same treatment.

In Windows and Node, we’ll take a look at Windows-centric Node development. In the first part, we’ll install Node (which now includes npm), take a look at the basics, then make a little Express web application to prove it’s generally portable with existing Node modules.

Installation

My Windows desktop

I’m running a pretty standard installation of Windows 7 Home Professional. I’ve got a few things I like installed (Steam, Putty, Chrome, Vim, Dropbox), but nothing specifically related to development. That means there’s no compilers, Cygwin, or Visual Studio.

Downloading Nodes Windows installer

To download Node, go to nodejs.org, click “Download”, and click “Windows Installer”. This will give you a Windows Installer (MSI) file that will install Node and npm.

Running the Node Windows installer

Running the Windows installer will show a wizard, it’s pretty easy to follow. It’s just like installing any other Windows program – the Node binaries will end up in C:\Program Files (x86)\nodejs\, and will be accessible from cmd.exe.

Running Node

Running Node and npm

To run Node, open a Command Prompt and type node. This will load the standard Node REPL where JavaScript can be evaluated. Here I’ve opened my win.ini using Node’s fs module:

Evaluating JavaScript

If you want to exit the REPL, I noticed that ctrl-d works (just like Unix!)

Similarly, npm can be run. The first time I used it to search for something, it took a few minutes to download the index first:

Using npm

Getting Help

When I’m working in Unix, I often find myself reading npm’s man pages. Windows doesn’t have man, so instead npm will open a browser and display HTML versions of its standard help files.

Getting help

The first time I tried this an error was displayed. However, there’s a bug report where fixes for the problem are discussed, and Isaac Schlueter stated that the problem will be fixed in Node 0.6.17.

Hello World from Express

Now that we’ve got Node and npm working it shouldn’t take too much work to get a little project started. Make a new directory somewhere and open your favourite editor. I’m using Vim, but you can use one of the many freely available editors for Windows.

Create a file called package.json:

{
  "name": "hello"
, "version": "0.0.1"
, "dependencies": {
    "express": "latest"
  }
}

Then change directory to the location of your project in Command Prompt, and run npm install to install Express:

cd Documents\Code\hello
npm install

Installing packages with npm

Make a file that contains a simple Express app, I called mine index.js:

var express = require('express')
  , app = express.createServer();

app.get('/', function(req, res) {
  res.send('hello world');
});

app.listen(3000)

Then run it with node index.js and visit http://localhost:3000/ in a browser.

I got a firewall warning when I did this, but it was fairly self-explanatory:

Windows Security Alert

Conclusion

On a standard consumer-grade version of Windows 7, Node can be installed and programs can be written without installing anything else. Building modules that require C/C++ compilation is a little bit more work, but community-favourite Express can be installed without any hassle.

In the coming weeks I hope to look at more detailed Windows-related issues, and working with Node and Microsoft technologies like Windows Azure. I bought a Windows 7 license specifically to write this series, so I’m going to get my money’s worth!

Node Roundup: 0.6.16, Node WebKit Agent, URLify, crud-bones, frontail

02 May 2012 | By Alex Young | Comments | Tags node modules unix url webkit
You can send in your Node projects for review through our contact form or @dailyjs.

Node 0.6.16

The latest stable release of Node is out: 0.6.16. V8 has been upgraded to 3.6.6.25, and there are improvements for each platform.

Dave Pacheco also posted about profiling Node with DTrace, but be forewarned that this is probably only useful if you’re able to run code on OpenSolaris-derived illumos systems. I actually use DTrace in Mac OS for debugging things that aren’t related to Node, but Dave notes that this won’t work due to the lack of ustack helpers, and invites readers to contact Apple about this:

OS X supports DTrace, but not ustack helpers. The way to get this changed is to contact your Apple developer liason (if you’re lucky enough to have one) or file a bug report at bugreport.apple.com. I’d suggest referencing existing bugs 5273057 and 11206497. More bugs filed (even if closed as dups) show more interest and make it more likely Apple will choose to fix this.

Node WebKit Agent

Node WebKit Agent (npm: webkit-devtools-agent) by Camilo Aguilar is an implementation of the Chrome developer tools protocol. This allows WebKit browsers to debug Node applications, which includes profiling, a console, and network monitoring.

A related project that I’ve used a few times is Node Inspector.

URLify

URLify (License: MIT, npm: urlify) by Enno Boland helps convert UTF-8 strings to ASCII that’s safe to use as a readable URL segment. For example:

var urlify = require('urlify').create({
  spaces: '_'
, nonPrintable: '_'
, trim: true
});

urlify('竹取物語 Taketori Monogatari');
// Taketori_Monogatari

crud-bones

crud-bones (GitHub: alexeypro / crud-bones) by Alexey Prohorenko is a boilerplate for Express-based apps that use MySQL, Mongo, or Redis. He’s also dotCloud and Heroku deployment instructions.

frontail

frontail

frontail (License: MIT, npm: frontail) by Maciej Winnicki is a WebSocket-based tail-inspired utility for watching logs. Imagine a version of tail that runs a little web server instead of writing to standard IO. It has some command-line options as well – for example, -n <number> will control how many lines are printed when it starts up.

jQuery Roundup: jQuery UI 1.8.20, jq-quickvalidate, Fullscreen Plugin

01 May 2012 | By Alex Young | Comments | Tags jquery jqueryui plugins validation fullscreen
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

jQuery UI 1.8.20

jQuery UI 1.8.20 has been released. This release marks the twentieth maintenance release, and includes bug fixes for Draggable, Sortable, and Datepicker.

jq-quickvalidate

jq-quickvalidate (License: GPLv2, Demo) by Cedric Ruiz is a form validation plugin. The author has provided CSS and icons, so it’s easy to drop into a site.

There are built-in validators, but custom ones can be added using a regular expression or function. Basic usage looks like this:

$('#my-form').quickValidate({
  inputs: {
    username: {
      filters: 'required username exclude',
      data: {
        exclude: ['Paul', 'Mike']
      }
    },
    'pass': {
      filters: 'required pass'
    }
  }
});

Fullscreen Plugin

jQuery Fullscreen Plugin (License: MIT) by Klaus Reimer is a jQuery-friendly API for working with the fullscreen mode present in supporting browsers. Vendor-specific versions are supported for WebKit and Firefox.

It can make an element or the entire document fullscreen:

$(document).fullScreen(true);
$('#myVideo').fullScreen(true);

It can also exit fullscreen, or check if fullscreen is currently active. A related plugin is jquery.fullscreen.js, which provides handling for various fullscreen-related events.