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.

Node Roundup: 0.9.11, clinch, review

06 Mar 2013 | By Alex Young | Comments | Tags node modules streams build graphics testing stats
You can send in your Node projects for review through our contact form.

Node 0.9.11

Node 0.9.11 was released last week, which has more changes for the new streams API. The _read method no longer takes a callback, which means your current _read methods need to be updated to call push() instead. If you’re unsure about the new API, Node’s tests (in test/simple) are useful for figuring out what to do.

These updates were pulled into isaacs/readable-stream, which is a module that allows you to use streams2 in Node 0.8. If you haven’t tried it yet, I recommend attempting to migrate your pre-0.10 custom streams to it, at least to prepare for Node 0.10.

clinch

clinch (GitHub: Meettya / clinch, License: MIT, npm: clinch) by Meettya is a CommonJS module to browser build system. It has a lot of features, some of which streamline working with CoffeeScript and Jade:

  • Builds are generated by analysing the source code
  • A fake global require function is not used, which means the client-side overheads are relatively low
  • It supports pre-compilation of Jade templates
  • And, it emulates Node globals, like process

The author has provided tests, but at the moment the documentation could do with some work – it’s written in English which isn’t the author’s native language, so perhaps someone could help him with that?

review

Julian Gruber sent in a whole bunch of modules, but the one I thought was cool was review (GitHub: juliangruber / review, License: MIT, npm: review). This module can be used to generate screenshots of sites according to various parameters – you could use it to check designs at various resolutions, for example.

Julian also sent in jilla which is a command-line client for JIRA, and statsc, a browser library for graphite/statsd servers.

jQuery Roundup: 2.0 Beta 2, Alpha Image, jqTree

05 Mar 2013 | By Alex Young | Comments | Tags jquery plugins tree widgets images Canvas
Note: You can send your plugins and articles in for review through our contact form.

jQuery 2.0 Beta 2

jQuery 2.0 Beta 2 is out, which has fixes for most of the major parts of the framework. This version also includes a Grunt build script, so you can build custom versions of jQuery more easily. The announcement posts suggests swapping out Sizzle for another selector engine.

jQuery 2.0 removes compatibility for IE before version 9, so you’ll have to use 1.9 if you want to support legacy browsers.

jQuery Alpha Image

jQuery Alpha Image (GitHub: Sly777 / Jquery-Alpha-Image, License: MIT/GPL, bower: Jquery-Alpha-Image) by İlker Güller uses a temporary Canvas to make a colour in an image transparent. It supports RGB and hex colours and has a callback that runs when the process has finished:

$('.example3').alphaimage({
  colour: '#9CDAF0',
  onlyData: true,
  onComplete: function(result) {
    console.log(result);
  }
});

jqTree

jqTree (GitHub: mbraak / jqTree, License: Apache 2.0) by Marco Braak is a widget that creates trees using unordered lists based on JSON data. It supports drag and drop for reordering items or moving them between parents, and supports IE7+.

The author has included tests, and the documentation is detailed, with lots of examples. The events API is thoughtful as well – you can even track when items are added to the tree with onCreateLi:

$('#tree1').tree({
  data: data,
  onCreateLi: function(node, $li) {
    // Add 'icon' span before title
    $li.find('.jqtree-title').before('<span class="icon"></span>');
  }
});

Layer, Thorax, Emacs.js, Chrome OS Dev

04 Mar 2013 | By Alex Young | Comments | Tags libraries node proxies editors backbone.js chrome-os

Layer

Layer (GitHub: lovebear / layer, License: BSD, npm: layer) by “lovebear” is a module for creating proxies without changing existing code. Given a function, it can augment it with another function that will run first. The returned values from the new function will be supplied as arguments to the original function.

The author’s example looks like this:

// add a simple proxy without modifying any existing code!
var addBig = function(x, y) {
  x = x * 100;
  y = y * 100;
  return [x, y];
}
layer.set(null, add, addBig);

// existing code...
function add(x, y) {
  return x + y;
}

add(2, 2); // 400

The layer.set method is used to invoke addBig before add, and passes the arguments to add. If you look at the source you’ll notice that the author has left a note saying “what if the return value isn’t an arrray?”, but it seems like the proxy functions should always map return values to the original function’s arguments.

Layer works in both Node and browsers.

Thorax

Thorax (GitHub: walmartlabs / thorax, License: MIT, npm: thorax) by Ryan Eastridge and Kevin Decker is another Walmart Labs project that brings together Backbone and Handlebars to provide an “opinionated, battle tested framework for building large scale web applications”.

Thorax has some sugar to help with tasks like data binding and events. Descendants of Thorax.View automatically have their properties mapped to template variables, and binding a model will cause the model’s attributes to be bound. Models and collections can also trigger view events, and events are inheritable.

Collections can also be rendered using the collection keyword in the template, and the views will stay current as models in the collection change.

It seems like Thorax fits in with my particular way of working with Backbone, and it looks like it might cut down a lot of the boilerplate I find myself writing so I’m going to give it a go.

emacs.js

If you’re looking for an easy to use solution for JavaScript development in Emacs, then take a look at emacs.js (GitHub: azer / emacs.js) by Azer Koculu. It comes with tools for npm, syntax checking and highlighting for JavaScript and CoffeeScript, and some snippets and autocompletion.

Azer make a screencast about it here: emacs.js screencast.

Chrome OS Development Follow Up

After I wrote about the Chromebook Pixel last week, I noticed a post in the Google+ Chromebook community about creating a Chrome OS development environment:

We really need to design and implement a proper application, extension, and theme development environment.

It could be implemented as a web ui page, as chrome://extensions/ is today, or even cooler, it could conceivably be its own packaged application.

My opinion on this is they should find a Chrome OS “native” way of making our existing development tools more accessible. I think being able to run Node and Vim/Emacs natively and sensibly on Chrome OS would be huge. I’m actually doing that in developer mode – Chrome OS is my GUI and I do development in a shell with Vim and tmux.

localStorage DOS, Lunr.js, Vlug

01 Mar 2013 | By Alex Young | Comments | Tags security libraries search benchmarking node

localStorage DOS

Even though the Web Storage specification says user agents should limit the amount of space used to store data, a new exploit uses it to store gigabytes of junk. The exploit is based around storing data per-subdomain, which gets around the limits most browsers have already implemented. Users testing it found Chrome would crash when run in incognito mode, but Firefox was immune to the attack.

Other security researchers have raised concerns about localStorage in the past. Joey Tyson talked about storing malicious code in localStorage, and Todd Anglin wrote about some of the more obscure facts about localStorage which touches on security.

Lunr.js

Oliver Nightingale from New Bamboo sent in his extremely well-presented full-text browser-based search library (GitHub: olivernn / lunr.js, License: MIT), which indexes JSON documents using some of the core techniques of larger server-side full-text search engines: tokenising, stemming, and stop word removal.

By removing the need of extra server side processes, search can be a feature on sites or apps that otherwise would not have warranted the extra complexity.

Trie is used for mapping tokens to matching documents, so if you’re interested in JavaScript implementations of data structures then take a look at the source. The source includes tests and benchmarks, and a build script so you can generate your own builds.

Vlug

Vlug (GitHub: pllee / vlug, License: MIT, npm: vlug) by Patrick Lee is a small instrumentation library for benchmarking code without manually adding log statements. The Vlug.Interceptor object takes a specification of things to log, which will dynamically invoke calls to console.time and console.timeEnd to collect benchmarks.

Patrick has tested it with browsers and Node, and has included Vlug.Runner for running iterations on functions. The readme and homepage both have documentation and examples.

Upgrading to Grunt 0.4

28 Feb 2013 | By Alex Young | Comments | Tags backbone.js node backgoog

I was working on dailyjs-backbone-tutorial and I noticed issue #5 where “fiture” was unable to run the build script. That tutorial uses Grunt to invoke r.j from RequireJS, and it turned out I forgot to specify the version of Grunt in the project’s package.json file, which meant newcomers were getting an incompatible version of Grunt.

I changed the project to first specify the version of Grunt, and then renamed the grunt file to Gruntfile.js, and it pretty much worked. You can see these changes in commit 0f98f7.

So, what’s the big deal? Why is Grunt breaking projects and how can this be avoided in the future?

Global vs. Local

If you’re a client-side developer, npm is probably just part of your toolkit and you don’t really care about how it works. It gets things like Grunt for you so you can work more efficiently. However, us server-side developers like to obsess about things like dependency management, and to us it’s important to be careful about specifying the version of a given module.

Previous versions of Grunt kind of broke this whole idea, because Grunt’s documentation assumed you wanted to install Grunt “globally”. I’ve never liked doing that, as I’ve experienced why this is bad first-hand with the Ruby side projects I’ve been involved with. What I’ve always preferred to do with Node is write a package.json for every project, and specify the version of each dependency. I either specify the exact version, or the minor version if the project uses semantic versioning.

For example, with Grunt I might write this:

 , "grunt": "0.3.x"

This causes the grunt command-line tool to appear in ./node_modules/.bin/grunt, which probably isn’t in your $PATH. Therefore, when you’re ready to build the project and you type grunt, the command won’t be found.

Knowing this, I usually add node_modules/.bin/grunt as a “script” to package.json which allows grunt to be invoked through the npm command. This works in Unix and Windows, which was partly the reason I used Grunt instead of make anyway.

There were problems with this approach, however. Grunt comes with a load of built-in tasks, so when the developers updated one of these smaller sub-modules they had to release a whole new version of Grunt. This is dangerous when a module is installed globally – what happens if an updated task has an API breaking change? Now all of your projects that use it need to be updated.

To fix this, the Grunt developers have pulled out the command-line part of Grunt from the base package, and they’ve also removed the tasks and released those as plugins. That means you can now write this:

 , "grunt": "0.4.x"

And install the command-line tool globally:

npm install -g grunt-cli

Since grunt-cli is a very simple module it’s safer to install it globally, while the part that we want to manage more carefully is locked down to a version range that shouldn’t break our project.

Built-in Tasks: Gone

The built-in tasks have been removed in Grunt 0.4. I prefer this approach because Grunt was getting extremely large, so it seems natural to move them out into plugins. You’ll need to add them back as devDependencies to your package.json file.

If you’re having trouble finding the old plugins, they’ve been flagged on the Grunt plugin site with stars.

Uninstall Grunt

Before switching to the latest version of Grunt, be sure to uninstall the old one if you installed it globally.

Other Changes

There are other changes in 0.4 that you may run into that didn’t affect my little Backbone project. Fortunately, the Grunt developers have written up a migration guide which explains everything in detail.

Also worth reading is Tearing Grunt Apart in which Tyler Kellen and Ben Alman explain why Grunt has been changed, and what to look forward to in 0.5.

Peer Dependencies

If you write Grunt plugins, then I recommend reading Peer Dependencies on the Node blog by Domenic Denicola. As a plugin author, you can now take advantage of the peerDependencies property in package.json for defining the version of Grunt that your plugin is compatible with.

Take a look at grunt-contrib-requirejs/package.json to see how this is used in practice. The authors have locked the plugin to Grunt 0.4.x.

Node Roundup: 0.8.21, Node Redis Pubsub, node-version-assets

27 Feb 2013 | By Alex Young | Comments | Tags node modules redis databases grunt
You can send in your Node projects for review through our contact form.

Node 0.8.21

Node 0.8.21 is out. There are fixes for the http and zlib modules, so it’s safe and sensible to update.

Node Redis Pubsub

Louis Chatriot sent in NRP (Node Redis Pubsub) (GitHub: louischatriot / node-redis-pubsub, License: MIT, npm: node-redis-pubsub) which provides a Node-friendly API to Redis’ pub/sub functionality. The API looks a lot like EventEmitter, so if you need to communicate between separate processes and you’re using Redis then this might be a good solution.

Louis says he’s using it at tl;dr in production, and the project comes with tests.

node-version-assets

node-version-assets (GitHub: techjacker / node-version-assets, License: MIT, npm: node-version-assets) by Andrew Griffiths is a module for hashing assets and placing the hash in the filename. For example, styles.css would become styles.7d47723e723251c776ce9deb5e23062b.css. This is implemented using Node’s file system streams, and the author has provided a Grunt example in case you want to invoke it that way.

jQuery Roundup: jQuery.IO, Animated Table Sorter, jQuery-ui-pic

26 Feb 2013 | By Alex Young | Comments | Tags jquery plugins forms json icons
Note: You can send your plugins and articles in for review through our contact form.

jQuery.IO

jQuery.IO (GitHub: sporto / jquery_io.js, License: MIT) by Sebastian Porto can be used to convert between form data, query strings, and JSON strings. It uses JSON.parse, and comes with tests and a Grunt build script.

Converting a form to a JavaScript object is just $.io.form($('form')).object(), and the output has form names as keys rather than the array results .serializeArray returns.

Animated Table Sorter

Animated Table Sorter (GitHub: matanhershberg / animated_table_sorter, License: MIT, jquery: AnimatedTableSorter) by Matan Hershberg is a table sorting plugin that moves rows using .animate when they’re reordered.

All you need to do is call .tableSort() on a table. CSS and images have been provided for styling the selected column and sort direction.

jQuery-ui-pic

jQuery-ui-pic (GitHub: rtsinani / jQuery-ui-pic) by Artan Sinani provides an extracted version of the icons from Bootstrap and the image sprites from jQuery UI.

In this version the CSS classes are all prefixed with pic-, so you can use them like this: <i class="pic-trash"></i>. This might prove useful if you’re looking for a quick way to reuse jQuery UI’s icons without using the rest of jQuery UI. I licensed Glyphicons Pro myself because I find myself using them so much.