Node Roundup: 0.11.0, Dependo, Mashape OAuth, node-windows

03 Apr 2013 | By Alex Young | Comments | Tags node modules dependencies oauth authentication windows
You can send in your Node projects for review through our contact form.

0.11.0, 0.10.2

Node 0.11.0 has been released, which is the latest unstable branch of Node. Node 0.10.12 was also released, which includes some fixes for the stream module, an update for the internal uv library, and various other fixes for cryptographic modules and child_process.

Dependo

Dependo

Dependo (GitHub: auchenberg / dependo, License: MIT, npm: dependo) by Kenneth Auchenberg is a visualisation tool for generating force directed graphs of JavaScript dependencies. It can interpret CommonJS or AMD dependencies, and uses MaDGe to generate the raw dependency graph. D3.js is used for drawing the results.

Mashape OAuth

Mashape OAuth (GitHub: Mashape / mashape-oauth, License: MIT, npm: mashape-oauth) by Nijiko Yonskai is a set of modules for OAuth and OAuth2. It has been designed to work with lots of variations of OAuth implementations, and includes some lengthy Mocha unit tests.

The authors have also written a document called The OAuth Bible that explains the main concepts behind each supported OAuth variation, which is useful because the OAuth terminology isn’t exactly easy to get to grips with.

node-windows

node-windows (GitHub: coreybutler / node-windows, License: MIT/BSD, npm: node-windows) by Corey Butler is a module designed to help write long-running Windows services with Node. It supports event logging and process management without requiring Visual Studio or the .NET Framework.

Using native node modules on Windows can suck. Most native modules are not distributed in a binary format. Instead, these modules rely on npm to build the project, utilizing node-gyp. This means developers need to have Visual Studio (and potentially other software) installed on the system, just to install a native module. This is portable, but painful… mostly because Visual Studio itself is over 2GB.

node-windows does not use native modules. There are some binary/exe utilities, but everything needed to run more complex tasks is packaged and distributed in a readily usable format. So, no need for Visual Studio… at least not for this module.

jQuery Roundup: Sidr, Huey, Backbone.Advice

02 Apr 2013 | By Alex Young | Comments | Tags jquery plugins backbone.js graphics components
Note: You can send your plugins and articles in for review through our contact form.

Sidr

Sidr

Sidr (GitHub: artberri / sidr, License: MIT) by Alberto Varela creates menus that look like the sidebars found in recent iOS apps. It can cope with multiple menus on a page, and can load content remotely. It’s also responsive, so it should work well in mobile projects.

The author has written up documentation complete with demos, and has included a Grunt build script. It seems like the exact sort of UI component that the next great web-based RSS reader might use…

Huey

Huey (GitHub: michaelrhodes / huey, License: MIT) by Michael Rhodes will find the dominant colour of an image and return it as an RGB array. This is all performed client-side, and doesn’t even depend on jQuery. It could be used to create the kind of effect seen in iTunes, where the background colour changes to suit the selected album art.

Backbone.Advice

Backbone.Advice (GitHub: rhysbrettbowen / Backbone.Advice, License: MIT) by Rhys Brett-Bowen is a Backbone plugin based on Angus Croll’s advice pattern. It basically adds functional mixins to Backbone objects, and can be wrapped like this:

Backbone.Advice.addMixin(Backbone.Views);

Rhys sent in a whole bunch of other Backbone-related projects, including Backbone.ComponentView and Backbone.ModelRegistry. Backbone.ComponentView is based on goog.ui.component from Closure Library, and also works with Backbone.Advice.

Five Minute Guide to Streams2

01 Apr 2013 | By Alex Young | Comments | Tags streams streams2 node 5min

Node 0.10 is the latest stable branch of Node. It’s the branch you should be using for Real Work™. The most significant API changes can be found in the stream module. This is a quick guide to streams2 to get you up to speed.

The Base Classes

There are now five base classes for creating your own streams: Readable, Writable, Duplex, Transform, and PassThrough. These base classes inherit from EventEmitter so you can attach listeners and emit events as you normally would. It’s perfectly acceptable to emit custom events – this might make sense, for example, if you’re writing a streaming parser. The parser could emit events like 'headers' to indicate the headers have been parsed, perhaps for a CSV file.

To make your own Readable stream class, inherit from stream.Readable and implement the _read(size) method. The size argument is “advisory” – a lot of Readable implementations can safely ignore it. Once your _read method has collected data from an underlying I/O source, it can send it by calling this.push(chunk) – internally data will be placed into a queue so “clients” of your class can deal with it when they’re ready.

The Writable class should also be inherited from, but this time a _write(chunk, encoding, callback) method should be implemented. Once you’ve written data to the underlying I/O source, callback can be called, passing an error if required.

The Duplex class is like a Readable and Writable stream in one – it allows data sources that transmit and receive data to be modelled. This makes sense when you think about it – TCP network sockets transmit and receive data. To implement a Duplex stream, inherit from stream.Duplex and implement both the _read and _write methods.

The Transform class is useful for implementing parsers, like the CSV example I mentioned earlier. In general, streams that change data in some way should be implemented using stream.Transform. Although Transform sounds a bit like a Duplex stream, this time you’ll need to implement a _transform(chunk, encoding, callback) method. I’ve noticed several projects in the wild that use Duplex streams with a stubbed _read method, and I wondered if these would be better served by using a Transform class instead.

Finally, the PassThrough stream inherits from Transform to do… nothing. It relays the input to the output. That makes it ideal for sitting inside a pipe chain to spy on streams, and people have been using this to write tests or instrument streams in some way.

Pipes

Pipes must follow this pattern: readable.pipe(writable). As Duplex and Transform streams can both read and write, they can be placed in either position in the chain. For example, I’ve been using process.stdin.pipe(csvParser).pipe(process.stdout) where csvParser is a Transform stream.

Inheritance

The general pattern for inheriting from the base classes is as follows:

  1. Create a constructor function that calls the base class using baseClass.call(this, options)
  2. Correctly inherit from the base class using Object.create or util.inherits
  3. Implement the required underscored method, whether it’s _read, _write, or _transform

Here’s a quick stream.Writable example:

var stream = require('stream');

GreenStream.prototype = Object.create(stream.Writable.prototype, {
  constructor: { value: GreenStream }
});

function GreenStream(options) {
  stream.Writable.call(this, options);
}

GreenStream.prototype._write = function(chunk, encoding, callback) {
  process.stdout.write('\u001b[32m' + chunk + '\u001b[39m');
  callback();
};

process.stdin.pipe(new GreenStream());

Forwards Compatibility

If you want to use streams2 with Node 0.8 projects, then readable-stream provides access to the newer APIs in an npm-installable module. Since the stream core module is implemented in JavaScript, then it makes sense that the newer API can be used in Node 0.8.

Some open source module authors are including readable-stream as a dependency and then conditionally loading it:

var PassThrough = require('stream').PassThrough;

if (!PassThrough) {
  PassThrough = require('readable-stream/passthrough');
}

This example is taken from until-stream.

Streams2 in the Wild

There are some interesting open source projects that use the new streaming API that I’ve been collecting on GitHub. multiparser by Jesse Tane is a stream.Writable HTML form parser. until-stream by Evan Oxfeld will pause a stream when a certain signature is reached.

Hiccup by naomik uses the new streams API to simulate sporadic throughput, and the same author has also released bun which can help combine pipes into composable units, and Burro which can package objects into length-prefixed JSON byte streams. Conrad Pankoff used Burro to write Pillion, which is an RPC system for object streams.

There are also less esoteric modules, like csv-streamify which is a CSV parser.

Edge.js, Bespoke.js, Barcode39

29 Mar 2013 | By Alex Young | Comments | Tags Canvas node Microsoft presentations libraries

Edge.js

Edge.js (GitHub: tjanczuk / edge, License: Apache 2, npm: edge) by Tomasz Janczuk is an in-process interoperability layer between .NET and Node. This allows things like CPU-bound operations to be processed by .NET, or Node to access the Win32 APIs through C#.

The .NET code can be executed asynchronously and may be passed as a multiline comment or a string. A basic example looks like this:

var edge = require('edge');

var helloWorld = edge.func('async (input) => { return ".NET Welcomes " + input.ToString(); }');

helloWorld('JavaScript', function(err, result) {
  if (err) throw err;
  console.log(result);
});

Running this example would display “.NET welcomes JavaScript”.

Other CLR languages can be supported, should you be interested in playing with F# for example.

This project requires Windows, and needs Visual Studio 2012, Python 2.7, and npm-gyp to build.

Bespoke.js

Bespoke.js

Bespoke.js (GitHub: markdalgleish / bespoke.js, License: MIT, bower: bespoke.js) by Mark Dalgleish is a small but slick presentation library. It works with keyboard and touch events, and is intended to be used with CSS transitions.

It’s built using ECMAScript 5, so you’ll want to run your presentations on a compatible browser.

Creating presentations involves wrapping HTML slide content in <section> containers. Horizontal and vertical deck styles are supported, and Mark has documented the CSS classes in the project’s readme so you can hook into the provided JavaScript and styles.

Barcode39

Barcode39 (GitHub: erik5388 / barcode-39.js, License: MIT) by Erik Zettersten is a Code 39 implementation – it basically generates barcodes that almost all barcode readers can cope with. It can output data URIs and supports Canvas for drawing.

The JavaScript API is new Barcode39(elementId, type, delimeter), but it will also look for an element with the default ID of barcode and read the element’s content for the barcode’s source text.

Backbone.js Tutorial: Updates for 1.0, Clear Complete

28 Mar 2013 | By Alex Young | Comments | Tags backbone.js mvc node backgoog bootstrap

Preparation

Before starting this tutorial, you’ll need the following:

  • alexyoung / dailyjs-backbone-tutorial at commit 711c9f6
  • The API key from part 2
  • The “Client ID” key from part 2
  • Update app/js/config.js with your keys (if you’ve checked out my source)

To check out the source, run the following commands (or use a suitable Git GUI tool):

git clone git@github.com:alexyoung/dailyjs-backbone-tutorial.git
cd dailyjs-backbone-tutorial
git reset --hard 711c9f6

Updating to Backbone 1.0

I updated bTask to work with Backbone 1.0, which required two small changes. The first was a change to the behaviour of callbacks in Backbone.sync – the internal call to the success callback now only needs one argument, which is the response data. I think I’ve mentioned that on DailyJS before, but you shouldn’t need to worry about this in your own Backbone projects unless you’ve written a custom Backbone.sync implementation.

The second change was the collection add events were firing when the views called fetch. I fixed this by passing reset: true to the fetch options. Details on this have been included in Backbone’s documentation under “Upgrading to 1.0”:

If you want to smartly update the contents of a Collection, adding new models, removing missing ones, and merging those already present, you now call set (previously named “update”), a similar operation to calling set on a Model. This is now the default when you call fetch on a collection. To get the old behavior, pass {reset: true}.

Adding “Clear Complete”

When a task in Google Tasks is marked as done, it will appear with strike-through and hang around in the list until it is cleared or deleted. Most Google Tasks clients will have a button that says “Clear Complete”, so I added one to bTask.

I added a method called clear to the Tasks collection which calls the .clear method from the Google Tasks API (rather than going through Backbone.sync):

define(['models/task'], function(Task) {
  var Tasks = Backbone.Collection.extend({
    model: Task,
    url: 'tasks',

    clear: function(tasklist, options) {
      var success = options.success || function() {}
        , request
        , self = this
        ;

      options.success = function() {
        self.remove(self.filter(function(task) {
          return task.get('status') === 'completed';
        }));

        success();
      };

      request = gapi.client.tasks.tasks.clear({ tasklist: tasklist });
      Backbone.gapiRequest(request, 'update', this, options);
    }
  });

  return Tasks;
});

I also added a button (using Bootstrap’s built-in icons) to app/js/templates/app.html, and added an event to AppView (in app/js/views/app.js):

var AppView = Backbone.View.extend({
  // ...
  events: {
    'click .clear-complete': 'clearComplete'
  },

  // ...
  clearComplete: function() {
    var list = bTask.views.activeListMenuItem.model;
    bTask.collections.tasks.clear(list.get('id'), { success: function() {
      // Show some kind of user feedback
    }});
    return false;
  }
});

I had to change app/js/views/lists/menuitem.js to set the current collection in the open method to make this work.

Summary

Because I’ve been reviewing Backbone’s evolution as it progressed to 1.0 for DailyJS, updating this project wasn’t too much effort. In general the 1.0 release is backwards compatible, so you should definitely consider upgrading your own projects. Also, now bTask has ‘Clear Complete’, I feel like it does enough of the standard Google Tasks features for me to actually use it regularly.

Remember that you can try it out for yourself at todo.dailyjs.com.

The full source for this tutorial can be found in alexyoung / dailyjs-backbone-tutorial, commit 705bcb4.

Node Roundup: wish, Vow, shell-jobs

27 Mar 2013 | By Alex Young | Comments | Tags node modules testing promises async time daemons unix
You can send in your Node projects for review through our contact form.

wish

wish (GitHub: EvanBurchard / wish, License: MIT, npm: wish) by Evan Burchard is an assertion module designed to raise meaningful, human-readable errors. When assertions fail, it parses the original source to generate a useful error message, which means the standard comparison operators can be used.

For example, if wish(a === 5) failed an error like this would be displayed:

WishError:
  Expected "a" to be equal(===) to "5".

If assert(a === 5) had been used instead, AssertionError: false == true would have been raised. A fairer comparison would be assert.equal, which would produce AssertionError: 4 == 5, but it’s interesting that wish is able to introspect the variable name and add that to the error.

Vow

Vow (GitHub: dfilatov / jspromise, License: MIT/GPL, npm: vow) by Filatov Dmitry is a Promises/A+ implementation. Promises can be created, fulfilled, and rejected – you should be able to get the hang of it if you’ve used libraries with then methods elsewhere, but there are some differences to Promises/A which feels like it actually simplifies some of the potentially messier parts of the original CommonJS specification.

Here’s an example of the Vow API:

var promise1 = Vow.promise(),
    promise2 = Vow.promise();

Vow.all([promise1, promise2, 3])
  .then(function(value) {
    // value is [1, 2, 3]
  });

promise1.fulfill(1);
promise2.fulfill(2);

The author has written some pretty solid looking tests, and benchmarks are included as well. The project performs favorably when compared to other popular promise libraries:

 mean timeops/sec
Q54.891ms18
When3.484ms287
Vow1.158ms864

shell-jobs

I like seeing daemons made in Node, and Azer Koçulu recently sent in a cron-inspired daemon called shell-jobs (GitHub: azer / shell-jobs, License: MIT, npm: shell-jobs). It uses .jobs files that are intended to be human readable. All you need to do is write a shell command followed by a # => and then a time:

cowsay "Hello" > /tmp/jobs.log # => 2 minutes

The shell-jobs script will then parse this file and output the following:

  jobs Starting "cowsay "Hello" > /tmp/jobs.log" [2 minutes] +2ms

After two minutes has passed the job will be executed:

  exec 1. Running cowsay "Hello" > /tmp/jobs.log. +0ms

jQuery Roundup: Individual Memberships, Bootstrap Tag Autocomplete, CDNJS

26 Mar 2013 | By Alex Young | Comments | Tags jquery plugins bootstrap cdn
Note: You can send your plugins and articles in for review through our contact form.

jQuery Foundation Individual Memberships

The jQuery Foundation has allowed corporations to become members for a year now, and they’ve just opened up the programme to individuals. If you’re interested in effectively sponsoring the jQuery Foundation, the jquery.com/join page has details on pricing and rewards.

Each pricing tier includes a gift, starting with a t-shirt, and the top $400 tier also includes “access to individual members only benefits at jQuery Foundation events”. I’m not sure what these individual benefits are, but where I come from $400 gets you a lot of benefits for your buck, so consider me cautiously intrigued.

Bootstrap Tag Autocomplete

When you’re writing Bootstrap-based projects, including any old jQuery plugin sometimes requires a bit of extra work to tailor the required markup and CSS to fit in with Bootstrap’s defaults. That means Bootstrap plugins are in demand from developers and designers. Nada Aldahleh recently sent in Bootstrap Tag Autocomplete (GitHub: Sandglaz / bootstrap-tagautocomplete, License: Apache 2.0), which is a Bootstrap and jQuery UI component for creating Twitter-like autocomplete interfaces.

It’s built on Bootstrap’s Typeahead library, and includes its own caret position library for getting and setting the caret position.

QUnit tests have been included, and the project’s website includes documentation and code samples.

CDNJS

Ryan Kirkman sent in CDNJS, which is an open source CDN. They’re looking for feedback on which libraries should be included – there are currently 325 listed. The code that runs the project is available on GitHub at cdnjs / cdnjs, and it’s based on Node.

Scripts can be added to the CDN by forking the GitHub project and following the instructions in the readme file. The general rule of thumb is that projects must have over 100 watchers on GitHub, but as long as sufficient popularity can be demonstrated the authors will consider including a new project. That means the list of libraries on cdnjs.com is useful for finding high quality scripts.

Dependent Types for JavaScript, radioactive.js, Minimail

25 Mar 2013 | By Alex Young | Comments | Tags computer-science education email apps

Dependent Types for JavaScript

Dependent Types for JavaScript published on Lambda the Ultimate is about Dependent JavaScript (DJS), a statically-typed dialect of JavaScript by Ravi Chugh, David Herman, and Ranjit Jhala (pdf):

DJS supports the particularly challenging features such as run-time type-tests, higher-order functions, extensible objects, prototype inheritance, and arrays through a combination of nested refinement types, strong updates to the heap, and heap unrolling to precisely track prototype hierarchies

The paper has a summary of related work that will be interesting to those of you who are experimenting with dialects of JavaScript with different type models.

radioactive.js

radioactive.js (GitHub: reinpk / radioactive, License: MIT) by Peter Reinhardt is a library for modelling nuclear physics. Its intended use is for creating interactive demonstrations of radioactive decay:

One of the biggest problems I’ve encountered in writing about nuclear reactors is that people don’t understand radioactive decay. This is a huge problem because it means that 99% of the population is totally unqualified to decide anything about nuclear energy.

Suppose I have 1 kg of Cesium-134, with a half-life of 30 years. And 1 kg of Uranium-238, with a half-life of 4.5 billion years. I’m going to give you one of the blocks, and you have to sleep with it tonight like a teddy bear. Which one do you want?

If you guessed Cesium-134, you’re dead.

So, if you often find yourself presented with various radioactive isotopes and don’t want to die, Peter’s library may be of use to you. Or else you’re creating presentations or simulations using D3.js that you want to have some level of accuracy.

Minimail

Minimail (GitHub: emailbox / minimail_mobileapp, License: BSD3) by Nicholas Reed is a mobile and server-side project to create a developer-friendly email client:

It is at the alpha stage, which means it kinda, sorta runs on Android and iOS, and is usable as a replacement mobile client (with changes synced to your Gmail web interface). I made it because there currently are no mobile email clients that are built with common frontend web languages. I’d like to see anyone able to run their own custom email client that fits their workflow.

It’s built using PhoneGap, and the server is Node with MongoDB.

KievII, Capturing, Mobify 2.0

22 Mar 2013 | By Alex Young | Comments | Tags audio mobile

KievII Host

The KievII audio plugin host

KievII Host (GitHub: janesconference / KievIIHost, License: MIT) by Cristiano Belloni is an audio plugin host based on the Web Audio API. The plugins are loaded dynamically using RequireJS from a GitHub repository, and already include lots of cool effects like a phaser, wah-wah, and pitch shift.

If you want to try out the KievII demo, which is a lot of fun, you’ll need Chrome and to enable Web Audio Input in chrome://flags. I tested it in Chrome 25 on a Mac and it ran pretty solidly. It allows audio to be routed from the mic through various effects, and there’s also a sample player with a keyboard for triggering audio samples at different pitches.

There’s more information about KievII at kievii.net, which has a demo of a step sequencer.

Capturing for Responsive Design

Shawn Jansepar sent in his post at the Mozilla Hacks blog, called Capturing - Improving Performance of the Adaptive Web, about a client-side API he’s developed called Capturing:

Our approach to give you resource control is done by capturing the source markup before it has a chance to be parsed by the browser, and then reconstructing the document with resources disabled.

The ability to control resources client-side gives you an unprecedented amount of control over the performance of your website.

Capturing was a key feature of Mobify.js 1.1, our framework for creating mobile and tablet websites using client-side templating. We have since reworked Mobify.js in our 2.0 release to be a much more modular library that can be used in any existing website, with Capturing as the primary focus.

One example Shawn uses is using a polyfill for the picture element, which only includes an extra img tag for browsers without JavaScript turned on. This is in contrast to other solutions that require noscript tags.

Mobify.js 2.0

Meanwhile, Mobify.js 2.0 (GitHub: mobify / mobifyjs, License: MIT) has been released as a developer preview. This includes the Capturing API mentioned in Shawn’s post above.

The goal of Mobify.js is to help existing sites better support mobile devices. The examples included are the picture polyfill mentioned above, using media queries, and templating.

Node Roundup: 0.10.1, Express Group Handlers, Fox, iWebPP.io

21 Mar 2013 | By Alex Young | Comments | Tags node modules express middleware testing p2p
You can send in your Node projects for review through our contact form.

Node 0.10.1

Node 0.10.1 has been released, hot on the heels of 0.10.0. This version improves the performance of the non-streaming crypto APIs, fixes some tls and net module issues, and makes missing callbacks in streams2 show a warning rather than raising an exception.

Express Group Handlers

Express Group Handlers (GitHub: tldrio / express-group-handlers, License: MIT, npm: express-group-handlers) by Louis Chatriot provides a little bit of sugar for managing Express middleware. It allows routes to be wrapped with beforeEach and afterEach so middleware can be confined to certain routes.

The beforeEach method can accept multiple middlewares to run, and it’s easy to wrap it around existing code:

var groupHandlers = require('express-group-handlers');

groupHandlers.setup(app);

app.beforeEach(groupHandler, function(app) {
  app.get('/route3', finalHandler3); // GET /route3 will execute groupHandler, then finalHandler3
});

Fox

Fox (GitHub: azer / fox, License: BSD, npm: fox) by Azer Koçulu is a test framework that is largely compatible with Mocha, as long as you don’t have nested invocations of describe. It works with both Node and client-side projects, and injects chai so you automatically get assertions without having to load an extra library.

Passing the -b flag to the command-line program will cause Fox to compile the scripts necessary to run the tests in a browser. It also includes tests written with itself, of course!

iWebPP.io

iWebPP.io (GitHub: InstantWebP2P / iwebpp.io, License: MIT, npm: iwebpp.io) by Tom Zhou is a set of projects designed to send HTTP over UDP, the goal being to take advantage of UDP’s inherent performance benefits. It supports TURN and STUN channeling with WebSockets, for realtime streaming.

It can run web services using peer-to-peer protocols, behind NAT and firewalls. The iwebpp.io module includes a binary called node-httpp, which provides the HTTP over UDP handling. The project includes installation instructions, and a brief roadmap.

I’ve seen a few peer-to-peer Node projects, but I think this is the first one I’ve seen that uses UDP as the transport layer protocol. It’s also interesting that the author is directly addressing NAT issues.

Backbone 1.0

20 Mar 2013 | By Alex Young | Comments | Tags backbone.js mvc libraries frameworks

Today Jeremy Ashkenas announced that Backbone.js 1.0 has been released, after a whole year on the 0.9 branch. This release adds support for HTTP PATCH requests, where partial updates are sent to the server. It also provides some sugar for data filtering methods like where and omit (from Underscore.js). Jeremy also notes that the annotated source has been improved.

Although Backbone 1.0 includes internal refactoring, the API should be largely backwards compatible – at least from the tests I’ve been doing with my own Backbone projects against the releases on GitHub. There may be quirks that I’ve missed, however, so as always make sure you’ve carefully tested your code before releasing it.

Jeremy also intimates that he’s looking for new major features, but doesn’t specifically promise anything in the roadmap:

In an ecosystem where overarching, decides-everything-for-you frameworks are commonplace, and many libraries require your site to be restructured to suit their look, feel, and default behavior - Backbone should continue to be a tool that gives you the freedom to design the full experience of your web application.

I feel like Backbone has earned its 1.0 status, and I’ll be watching Backbone’s GitHub repository very carefully over the next few months.

jQuery Roundup: Panzoom, jQuery.Feedback, shurikenJS

19 Mar 2013 | By Alex Young | Comments | Tags jquery plugins animation frameworks
Note: You can send your plugins and articles in for review through our contact form.

Panzoom

Panzoom (GitHub: timmywil / jquery.panzoom, License: MIT) by Timmy Willison is a plugin for adding panning and zooming behaviour to an element. It works in jQuery 1.9+, and uses CSS transforms and matrix functions to take advantage of GPU acceleration where available.

Any element can be potentially panned or zoomed, including Canvas and videos. It supports touch gestures, including pinch, so it should work well in a mobile project.

There’s a demo in the form of Panzoom’s unit tests.

jQuery.Feedback

jQuery.Feedback (GitHub: siong1987 / jquery.feedback, License: MIT) by Teng Siong Ong is a clone of the feedback widget found on Branch. It has some nice CSS transform animations, and just expects a callback for handling sending the resulting message.

shurikenJS

shurikenJS

shurikenJS (GitHub: shurikenjs, License: MIT) by Stephan Fischer is a JavaScript framework that uses recent ECMAScript methods and an API based around native DOM objects. The Node object is enhanced with new chainable methods, for example: Node.css('color', 'red').hide().show().

Stephan hasn’t included any tests yet, but I’ve included it here because it’s so different to jQuery it should get you thinking. The combination of modern ECMAScript with native DOM code is an interesting approach to client-side development.

OrganicJS, HALbert, BromBone

18 Mar 2013 | By Alex Young | Comments | Tags node libraries graphics frameworks api

OrganicJS

OrganicJS (GitHub: idibidiart / organicjs) by Marc Fawzi is a reusable component framework, which combines ideas from the author’s previous work with D3.js. It supports chainable properties, dynamic getters and setters, reusable and nestable markup, in-place fragment cloning and rendering, and decoupled data/behaviour sharing across components.

The project is currently in an early state, without much documentation or tests, but Marc is looking for feedback on the project. If you want to try it out, the best way to get started is by looking at the OrganicJS demo site.

HALbert

HALbert (GitHub: xcambar / halbert, License: MIT, npm: halbert) by Xavier Cambar is a HAL-JSON parser:

There is an emergence of non-HTML HTTP applications (“Web APIs”) which use hyperlinks to direct clients around their resources.

The JSON Hypertext Application Language (HAL) is a standard which establishes conventions for expressing hypermedia controls, such as links, with JSON RFC4627.

HAL is a generic media type with which Web APIs can be developed and exposed as series of links. Clients of these APIs can select links

It can be used as a Node module or in browsers, through Browserify. The author has designed it to work pretty much anywhere in your application’s stack: Express middleware, or in client-side frameworks like Backbone or AngularJS.

BromBone

Although PhantomJS is extremely useful, there are times when you don’t want to include the dependency in a server-side project. I’ve considered making my own mini REST services for such cases, so the “heavier” dependencies like PDF generation or PhantomJS are split off into their own self-contained projects. But why bother building such services at all? Surely there are suitable APIs that can be used from services like Heroku and Nodejitsu?

Enter BromBone, by Chad DeShon. BromBone is a web service for PhantomJS, with a simple API and reasonable pricing. It currently allows a page to be rendered as a PNG with an optional delay, and can also run JavaScript on a page. Chad only released the project recently so he’s looking for new users to try it out.

WebGL Head Tracking, Clouseau, ColtJS

15 Mar 2013 | By Alex Young | Comments | Tags webgl mvc testing node

WebGL Head Tracking

headtrackr

In Move a Cube With Your Head or Head-Tracking With WebGL, Jerome Etienne talks about 3D head tracking using Three.js and WebRTC. He’s using a library for face and head tracking called headtrackr by Audun Mathias Øygard, which has been used to create some interesting demos and games (check out Targets and FaceKat).

Clouseau

Clouseau (GitHub: hull / clouseau, License: MIT, npm: clouseau-js) by Xavier Cambar tracks applications using PhantomJS combined with Q. It basically provides a lightweight integration testing solution:

Once you’ve defined invariants in your app, you provide Clouseau with functions to assert them. Then Clouseau will open in PhantomJS the URL at which your app resides and will applies these functions.

It can be used for testing, but the author also notes it works for monitoring long-running applications.

ColtJS

ColtJS (GitHub: Fluidbyte / ColtJS, License: MIT) is a framework for creating AMD-based applications. It supports routing, templates, URL parsing, network calls, events, storage, and pub/sub:

ColtJS is a simple framework allowing for easy deployment of JavaScript Application using asynchronous module definition. Its only dependency is RequireJS and it builds off simple principles of a centralized router loading modules only when requested to produce an efficient, easy-to-manage application structure.

Backbone.js Tutorial: Customising the UI

14 Mar 2013 | By Alex Young | Comments | Tags backbone.js mvc node backgoog bootstrap

Preparation

Before starting this tutorial, you’ll need the following:

  • alexyoung / dailyjs-backbone-tutorial at commit 85c358
  • The API key from part 2
  • The “Client ID” key from part 2
  • Update app/js/config.js with your keys (if you’ve checked out my source)

To check out the source, run the following commands (or use a suitable Git GUI tool):

git clone git@github.com:alexyoung/dailyjs-backbone-tutorial.git
cd dailyjs-backbone-tutorial
git reset --hard 85c358

Customising Bootstrap

Before customisation.

So far our Backbone application has had a rudimentary interface. It’s based on Bootstrap, which is a popular choice for developers who want a usable interface without spending too much time working on the design side of things. However, Bootstrap is a victim of its own popularity, and most of us are starting to grow tired of seeing it everywhere.

This post is about techniques for customising projects built with Backbone and Bootstrap. There are three main approaches I use to add some originality to my Bootstrap projects:

  1. Colours: Get the project configured with suitable branding
  2. Texture: Judicious use of images to add an extra dimension to background, panels, and buttons
  3. Custom fonts and icons: Carefully applied custom fonts and icons can create a more distinct look

Colours

Bootstrap has a customisation page that allows you to change typographic elements and colours. This is self-explanatory so I’m not going to spend too much time on it. Bootstrap is built on LESS CSS so it’s easy to create your own builds of Bootstrap with custom colours baked right in.

Texture

Subtle Patterns.

To save time when working on client projects, I’ll often dig through stock photography sites to find useful illustrations and textures. This project, however, just needs something to add a texture to the left-hand-side navigation to make it look visually distinct. An excellent resource for textures is Subtle Patterns – a curated directory of tiled textures suitable for web and mobile projects. For legal information for use in commercial projects, see About Subtle Patterns.

I’ve added two tiled images to the project: one for the navigation bar and another for the body background. The image used on the body is white, while the navigation bar is dark grey. The navigation list elements use alpha blending to make the underlying texture appear lighter, with rgba(255, 255, 255, .25).

It’s easy to add textures to a project, particularly when they tile, and the Subtle Patterns images include a higher-DPI version as well. I find this a fun second stage to Bootstrap customisation, because it’s easy to quickly swap textures around to experiment.

Custom Fonts and Icons

Using Google Web Fonts.

The first thing I wanted to change was the logo font. Rather than using an image I found a suitable font on Google Web Fonts and applied some CSS shadows. This font was added to the project by updating index.html to load the font and updating the CSS to refer to it by name:

<link href='http://fonts.googleapis.com/css?family=Playball' rel='stylesheet' type='text/css'>

Then in the CSS the font is selected with font-family: playball, sans-serif.

I also switched the main body font to PT Sans, which doesn’t look radically different to the default but again elevates the look and feel away from stock-Bootstrap.

Another quick win is to use Font Awesome.

Go Forth and Customise

The finished article.

Adding custom fonts, textures, and icons are just a few easy ways to distinguish a Bootstrap-based project from the crowd. You’ve got no excuse for releasing boring-looking apps!

I’m running a build of bTask at todo.dailyjs.com. It’s not exactly the same as the tutorial version at the moment because I wrote it while researching this tutorial series, but eventually I’ll switch it over to use the same code as the GitHub project. It doesn’t implement everything Google Tasks supports (like subtasks for example), but I use it every day at work.

The full source for this tutorial can be found in alexyoung / dailyjs-backbone-tutorial, commit 711c9f6.

Node Roundup: 0.10, Versions, cors

13 Mar 2013 | By Alex Young | Comments | Tags node modules middleware servers
You can send in your Node projects for review through our contact form.

Node 0.10.0

It’s finally here! Node 0.10.0 has been released, which means your custom streams can now be rewritten with the new primitive classes. This is a good thing. The announcement post has a lot of details on benchmarks, and mentions the new Node CI server that shows the build status for each of the platforms Node officially supports.

… all streams in Node-core are built using the same set of easily-extended base classes, so their behavior is much more consistent, and it’s easier than ever to create streaming interfaces in your own userland programs.

Isaac mentions 37 modules are using the readable-stream module. This module allows streams2 to be used with Node 0.8 applications, so you can use it as a bridge to migrate older code. There are also streams2 modules already out there – for example, tub by Eirik Albrigtsen uses the new Transform class.

The road to 1.0.0 will see a Node 0.12 series released first. The goal of 0.12 will be to improve Node’s HTTP implementation, which will involve improving the encapsulation between client and server code and reworking the socket pooling behaviour.

Versions

Versions (GitHub: 3rd-Eden / versions, License: MIT, npm: versions) by Arnout Kazemier is a module for creating a content delivery network. It was designed to address performance concerns when using Node for serving static assets when compared to servers that support sendfile like Nginx. It does things like sets the correct HTTP caching headers, and has a REST API for server management which also outputs various metrics.

Arnout wrote a great introduction to Versions, Versions: The Node.js Content Delivery Network, which explains how to configure the application as well as demonstrating the improvements it offers.

cors

cors (GitHub: TroyGoode / node-cors, License: MIT, npm: cors) by Troy Goode is Express/Connect middleware for working with cross-origin resource sharing. This allows your Express apps to accept cross-origin requests by writing out the appropriate HTTP headers.

The readme includes an asynchronous example that illustrates how to conditionally accept requests. You could use it to whitelist specific domains for apps that are configured for multiple domains.

jQuery Roundup: jQuery-menu-aim, Toolbar, ngInfiniteScroll

12 Mar 2013 | By Alex Young | Comments | Tags jquery plugins usability menus toolbars pagination
Note: You can send your plugins and articles in for review through our contact form.

jQuery-menu-aim

jQuery-menu-aim (GitHub: kamens / jQuery-menu-aim, License: MIT) by Ben Kamens is a for making large dropdowns in a similar style to Amazon. Ben has written a post about why this is desirable: Breaking Down Amazon’s Mega Dropdown.

At every position of the cursor you can picture a triangle between the current mouse position and the upper and lower right corners of the dropdown menu. If the next mouse position is within that triangle, the user is probably moving their cursor into the currently displayed submenu. Amazon uses this for a nice effect. As long as the cursor stays within that blue triangle the current submenu will stay open

Ben made a diagram of this to visualise the area used to detect the mouse.

jQuery-menu-aim

I thought this was a great piece of work, both from the developers at Amazon and Ben in recognising something interesting was going on behind the scenes. The plugin comes with an example, and has configuration options for integrating it with your existing markup.

Toolbar

Toolbar

Toolbar (GitHub: paulkinzett / toolbar, License: MIT, jQuery: toolbar) by Paul Kinzett is a plugin for quickly creating popup toolbars with icons. The markup is an unordered list, and the toolbar can be oriented both vertically and horizontally.

The plugin includes CSS and icons, so it can be dropped straight into a project and should look similar to the examples on the site.

ngInfiniteScroll

ngInfiniteScroll (GitHub: BinaryMuse / ngInfiniteScroll, License: MIT, npm: ng-infinite-scroll) is an AngularJS project that depends on jQuery which can help implement infinite scrolling. It’s used by adding the infinite-scroll attribute to an element, and then implementing a controller that can fetch data when required.

The remote data demo shows how it works by calling Reddit’s JSONP API.

Node 0.10

11 Mar 2013 | By Alex Young | Comments | Tags node

Node 0.10 is about to be released – the next stable version of Node. The most major change is the new streams API, which is designed to overcome some of the limitations found in previous versions. For a summary of the issues with streams in Node 0.8 and the new API, see: A New Streaming API for Node v0.10.

At first the new streams API seems quirky to work with, but I’m convinced my streams2 code is leaner. There are also new base classes for streams: Readable, Writable, Duplex, and Transform. These classes actually cover some key functionality that was previously provided by third party modules.

Many of Node’s core modules have streaming interfaces, and 0.10 adds streaming APIs to the crypto module.

EventEmitter has some changes. The documentation recommends using util.inherits to extend the EventEmitter class, and I’d add that it’s a good idea to call the constructor as well. There’s also a new removeListener event which is emitted when listeners are removed, including when removeAllListeners is called.

setImmediate semantics in Node 0.9.x

Node now has setImmediate and clearImmediate – there’s a useful diagram by Shigeki Ohtsu that shows where setImmediate is triggered: setImmediate semantics in Node 0.9.x.

For more details on API changes, see Api changes between v0.8 and v0.10.

Validatr, pointeraccuracy.js, Testacular Updates

Validatr

Validatr logo

Validatr (GitHub: jaymorrow / validatr, License: MIT, jquery: validatr) by Jay Morrow is a cross-browser HTML5 form validation library. That means it provides validators for the new native widgets, like color and date. The Validatr fields documentation lists all of the supported inputs and also features demos.

The library requires jQuery, and usage looks like this:

$('form').validatr('addTest', 'example', function(element) {});

Jay has also included QUnit tests for Validatr.

pointeraccuracy.js

pointeraccuracy.js (GitHub: n-fuse / pointeraccuracy.js, License: MIT) by Thomas Hoppe is a polyfill for the media query level 4 property “pointer”. This API heuristically determines the pointer accuracy, returning coarse or fine depending on the input device’s accuracy:

This media feature does not indicate that the user will never be able to click accurately, only that it is inconvenient for him to do so. Authors are expected to react to a value of coarse by designing pages that do not rely on accurate clicking to be operated.

Testacular Updates

Testacular, used by the AngularJS team, has been updated. The new version includes code coverage, Growl and TeamCity reporters, and an adapter for QUnit.

Vojta Jína posts about the project to his Google+ account: +Vojta Jína.

Backbone.js Tutorial: Routes

07 Mar 2013 | By Alex Young | Comments | Tags backbone.js mvc node backgoog

Preparation

Before starting this tutorial, you’ll need the following:

  • alexyoung / dailyjs-backbone-tutorial at commit 0c6de32
  • The API key from part 2
  • The “Client ID” key from part 2
  • Update app/js/config.js with your keys (if you’ve checked out my source)

To check out the source, run the following commands (or use a suitable Git GUI tool):

git clone git@github.com:alexyoung/dailyjs-backbone-tutorial.git
cd dailyjs-backbone-tutorial
git reset --hard 0c6de32

Routes

So far we’ve implemented basic list and task management, but working with multiple lists is tricky because lists can’t be referenced by the URL. If the page is reloaded, the current list isn’t remembered, and lists can’t be bookmarked.

Fortunately, Backbone provides a solution for both of these issues: Backbone.Router. This provides a neat wrapper around hash URLs and history.pushState.

When to Use Hash URLs

I’ll admit I find hash URLs annoying, and this sentiment seems to have been perpetuated by Twitter’s implementation of them. However, there is a good side to hash URLs: they require less work to build and are backwards compatible with older browsers.

Using history.pushState means the browser can potentially display any URL you want. Rather than /#lists/id, the prettier /lists/id can be displayed. However, without a suitable server-side setup, visiting /lists/id before the main application has loaded will fail while the hash URL version will work.

If you’re making a fairly simple and self-contained single page application, then you may wish to avoid pushState and use hash URLs instead.

Either way, Backbone makes it easy to switch between both schemes. Hash URLs are the default, and history.pushState will be used when specified with Backbone.history.start({ pushState: true }).

The Routes File

It’s generally a good idea to keep routes separate from the rest of the application. Create a new file called app/js/routes.js and extend Backbone’s router:

define(function() {
  return Backbone.Router.extend({
    routes: {
      'lists/:id': 'openList'
    },

    initialize: function() {
    },

    openList: function(id) {
    }
  });
});

This code defines the route. This application will just need one for now: lists/:id. The :id part is a parameter, which will be extracted by Backbone.Router and sent as an argument to openList.

Load the Router

The centralised App class is as good a place as any to load the routes and set them up. Open app/js/app.js and change define to include 'routes':

define([
  'gapi'
, 'routes'
, 'views/app'
, 'views/auth'
, 'views/lists/menu'
, 'collections/tasklists'
, 'collections/tasks'
],

function(ApiManager, Routes, AppView, AuthView, ListMenuView, TaskLists, Tasks) {
  var App = function() {
    this.routes = new Routes();

Now, move down to around line 35 where there’s a callback that runs when the API manager is ready. This is where Backbone.history.start should be called:

App.prototype = {
  views: {},
  collections: {},
  connectGapi: function() {
    var self = this;
    this.apiManager = new ApiManager(this);
    this.apiManager.on('ready', function() {
      self.collections.lists.fetch({ data: { userId: '@me' }, success: function(collection, res, req) {
        self.views.listMenu.render();
        Backbone.history.start();
      }});
    });
  }
};

It’s technically safe to call this when the routes have been loaded, but the openList route handler requires that some lists exist, so it’s better to load it when the API is ready.

The purpose of the start method is to begin monitoring hashchange events – whenever the browser address bar’s URL changes the router will be invoked.

Opening Lists Using Events

To write decoupled Backbone applications, you need to think in terms of the full Backbone stack: models and collections, and views. When someone visits a list URL from a bookmark that refers to a specific model, the route handler should be able to find the associated model.

Backbone’s documentation is quite clear about the power of custom events, and that’s basically how openList in app/js/routes.js should work:

openList: function(id) {
  if (bTask.collections.lists && bTask.collections.lists.length) {
    var list = bTask.collections.lists.get(id);
    if (list) {
      list.trigger('select');
    } else {
      console.error('List not found:', id);
    }
  }
}

I’ve been strict about checking for the existence of the lists collection, and even when fetching a given list model from the collection. The main reason for this was to be able to show sensible error messages, but for now there’s just a console.error to help track issues loading data.

The final piece of the puzzle is the view code that has the responsibility of opening lists. Open app/js/views/lists/menuitem.js and make the following changes:

  1. Add this.model.on('select', this.open, this); to the initialize method
  2. Add bTask.routes.navigate('lists/' + this.model.get('id')); to the render method

The first line binds the custom event, select, from the view’s model (which represents the list). The second line causes the browser’s URL to be updated – you’ll find yourself using routes.navigate quite a lot in more complicated applications.

Summary

Combining events and routes is the secret to writing decoupled Backbone applications. It can be difficult to do this well – there are definitely often lazy solutions that can result in a little bit too much spaghetti code. To avoid situations like this, think in terms of models, collections, views, and their relationships.

The full source for this tutorial can be found in alexyoung / dailyjs-backbone-tutorial, commit 85c358.