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.

quotefm-node, Pin, Boots

30 Apr 2012 | By Alex Young | Comments | Tags node modules

quotefm-node

quotefm-node (License: MIT, npm: quotefm) by Enno Boland is a module for working with the QUOTE.fm API. It can be used to get recommendations, articles, and user information back from the service.

The module includes some good documentation, and the QUOTE.fm API documentation is also easy to follow as well.

Pin

Pin (License: MIT, npm: pin) by Veselin Todorov is a small module for uptime monitoring:

pin('http://google.com/')
  .interval(10000) // in ms
  .up(function(response) {
      console.log(response);
   })
  .down(function(error, response) {
    console.log(error, response);
  });

The chainable API also allows HTTP headers to be set.

Boots

Boots (GitHub: jgallen23 / boots, npm: boots) by Greg Allen is a command-line utility for building custom Bootstrap asset files.

If .less files are passed to it then a CSS file will be generated:

boots --js bootstrap-modal.js,bootstrap-tooltip.js --css modals.less,tooltip.less -o public/bootstrap

PinClusterer, Backbone.Routes, Rice, Fiddle.js

27 Apr 2012 | By Alex Young | Comments | Tags node geo maps backbone.js databases

PinClusterer

PinClusterer

PinClusterer (GitHub: rtsinani / PinClusterer) by Arti Sinani is a library for clustering pins on Bing maps. Pins are grouped together based on a grid size setting:

var pinClusterer = new PinClusterer(map, {
  gridSize: 40
});
pinCluster.cluster(data);

pinCluster.setOptions({ gridSize: 30 });
pinCluster.cluster();

The pin settings are all configured the same way as a standard Microsoft.Maps.Pushpin. The author has included a stylesheet that will create circular icons with a shadow and gradient.

Backbone.Routes

Backbone.Routes (License: MIT) by Teng Siong Ong is an alternative API for routing in Backbone.js. It helps centralise routes, and can trigger multiple routes for a given URL.

It seems more like the way Rails routing works, and the author indicates he’s been influenced by Rails in the project’s source code. Here’s an example:

Backbone.Routes.prefix = YourApp.Routers

Backbone.Routes.map
  '/':
    'NavbarRouter': 'index'
    'HomeRouter': 'index'

Rice

Rice (License: MIT) by Yuri Neves is a database library that uses the Web SQL Database API. Although Firefox supports Indexed DB instead, this API can be used with PhoneGap.

Usage looks like this:

rice.use('myDb')
  .select({ from: 'People', where: { age: 21 } }, function(result) {
    result.each(function(row) {
      $('<li>').html(row.name).appendTo('#myList');
    });
  });

The source is available here: rice.jscraft.org/src/rice.js.

Fiddle.js

Fiddle.js (License: MIT, npm: fiddle) by Craig Condon is a MongoDB-inspired object manipulation library. Operators like $inc, $set, $unset, and more are supported.

The fiddle method itself accepts a modifier object, and then filters and targets. The targets represent the data to modify:

// Increment age by one
var fiddled = fiddle({ $inc: { age:1 } }, null, { name: 'Craig', age: 21 });

The results returned by fiddle can be filtered and otherwise iterated over.

Unix and Node: IPC

26 Apr 2012 | By Alex Young | Comments | Tags node tutorials unix ipc

This tutorial explores the world of inter-process communication (IPC) in Unix, and solutions for Node developers. IPC actually covers a broad swathe of methods, including POSIX signals and pipes, which we’ve already covered in this series. Here I’m only going to cover IPC methods that are based on sockets or Unix domain sockets.

IPC

IPC enables structured data to be shared between processes. In terms of architecture, scaling software by creating smaller programs that communicate with each other using simple data formats fits in with the Unix philosophies mentioned previously in this series. Additionally, it may be desirable to use established Unix-based IPC systems from within Node.

Beyond modularity and performance, IPC can also be used to restrict privileged access to certain resources. For example, a Node web application could run on a registered port (above 1023) which is generally accessible by ordinary user accounts. Then another program with additional privileges to access port 80 could proxy requests to it, thereby limiting access and potentially improving security.

It’s likely that contemporary developers that don’t come from a Unix background will already use IPC and RPC. Message queues in particular are very popular now – ZeroMQ can be configured to communicate locally using its IPC transport that’s based on Unix domain sockets

D-Bus

D-Bus supports many POSIX operating systems. It’s most closely associated with KDE, but can be installed on Mac OS, and there’s even a Windows port. It can use Unix or IP sockets.

D-Bus generally runs as a system-level daemon, and also as a session daemon:

A GNOME environment normally runs two kinds of buses: a single system bus for miscellaneous system-wide communication, e.g. notifications when a new piece of hardware is hooked up; and a session bus used by a single user’s ongoing GNOME session.

The two most popular Node implementations are node-dbus (License: MIT, npm: dbus) by Shouqun Liu, and node-dbus (License: BSD, npm: node-dbus) from Motorola Mobility. They’re both built using C++ extensions that wrap around the libdbus APIs.

It’s unlikely that D-Bus is (or will be) a popular solution for IPC with Node developers, but it does allow us to integrate more tightly with desktop environments. For example, if I use a GNOME music player that exposes services through D-Bus, I could write Node scripts that monitor what I’m listening to and post the data to Last.fm. Linux Journal has a general article on this topic that serves as a basic introduction: Control Your Linux Desktop with D-Bus.

Homegrown IPC and RPC

There are dozens of modules that provide IPC and RPC solutions that are aimed at Node developers without integrating with existing high-level Unix daemons.

DNode by James Halliday is one such example that works with Unix domain sockets, TCP streams, or WebSocket. It’s an RPC implementation that uses a newline-terminated JSON protocol which is documented in the dnode-protocol module.

There’s also thintalk (License: MIT, npm: thintalk) by Andreas Madsen that implements a lightweight RPC layer. It’s aimed at pure Node environments, unlike DNode which can be called from different programming languages and browsers.

Easy IPC (License: MIT, npm: easy-ipc) by Oliver Leics is an event-based IPC implementation. It supports newline-terminated JSON streams, but can work with plain text as well.

Message Queuing

The ØMQ messaging library is lightweight, high-performance, and asynchronous. The zmq (License: MIT, npm: zmq) module by Justin Tulloss is a popular solution, with an idiomatic Node API.

ØMQ runs on Linux, Windows, and Mac OS, and specifically targets fast performance. In contemporary discussions on IPC, it’s often cited as a suitable alternative to legacy message brokers.

Conclusion

IPC is an incredibly broad term that covers using files for communication, signals, sockets, message queues, pipes, shared memory, and pretty much everything else. I’m still searching for a quantum-entanglement IPC solution for Unix.

It’s therefore difficult to keep this discussion focused on Unix, particularly as modern systems like ØMQ will run just about anywhere. However, I hope that by mentioning D-Bus, Node hackers who run desktop systems like KDE or GNOME might be inspired to rewire their desktops in all kinds of creative ways.

Node Roundup: node-webcl, node-webgl, node-glfw

25 Apr 2012 | By Mikael Bourges-Sevenier | Comments | Tags node modules webgl webcl
You can send in your Node projects for review through our contact form or @dailyjs.

Mikael Bourges-Sevenier has sent in three WebGL and WebCL modules that he’s written for Node. We’ll resume our regularly scheduled Node Roundup posts next week!

node-webcl

node-webcl (GitHub: Motorola-Mobility / node-webcl, License: BSD, npm: node-webcl) from Motorola Mobility is an implementation of the Khronos WebCL working draft using Node. It has been tested on Mac OS X 10.7 and Linux. It should also work on Windows 7. Its only dependency is node-webgl, another Node module that implements the WebGL standard.

The module contains various tests and sample applications to help developers leverage multiple CPU and GPU cores. It is also used as a tool to develop experimental features that may or may not be in the WebCL standard.

Installing node-webcl with npm will fetch node-webgl and node-glfw. Since they rely on native libraries, make sure they’re available:

There are more details in the project’s readme. Intel’s OpenCL SDK can also be installed as a pure WebCL implementation, and be sure to check you’ve got the latest drivers installed for your graphics card.

node-webgl

node-webgl (GitHub: mikeseven / node-webgl, License: BSD, npm: node-webgl) is an implementation of the Khronos WebGL specification. This is a fork of Tim Caswell’s WebGL project that started life as Blue GPU Lava at Node Knockout.

This module allows WebGL applications originally created for browsers to run using Node on the desktop without modification. It provides support for DOM methods commonly used to create WebGL content.

Like node-webcl, this module has been tested with Mac OS X and Linux. It relies on GLEW, GLFW, and AntTweakBar. Lots of samples have been included – some show how to use AntTweakBar to create a compelling GUI.

node-glfw

Finally, node-glfw (GitHub: mikeseven / node-glfw, License: BSD, npm: node-glfw) is a JavaScript wrapper around GLFW. This provides implementations, where possible, of WebGL methods on top of desktop OpenGL as well as a browser compliant event model.

Although this module will run on Node 0.6, at least 0.7.5 is recommended for the typed array support. This module is intended as a platform-level binding – node-webgl should be used to create OpenGL applications.