MVC: Primer

12 Jul 2012 | By Alex Young | Comments | Tags mvc tutorials

I recently attended a talk by Addy Osmani at the London Ajax Group (great meetup by the way) in which Addy discussed client-side MVC. The slides are available here: Digesting JavaScript MVC – Pattern Abuse Or Evolution?

Since then I’ve been thinking a lot about client-side MVC. Rather than simply mentioning frameworks like Backbone.js as part of regular roundup style posts, I thought it might be useful to dig a little deeper into the client-side MVC phenomenon.

The Elephant in the Room

We’re stuck with the term “MVC”. It’s not an accurate way to describe what frameworks like Backbone.js do, but to avoid confusing matters I’ll stick with it for now. Some libraries and frameworks seek to differentiate themselves by using more accurate terms like MVVM (Model-View-View Model).

Terminology aside, most client-side developers are probably in a position where they think they need something like Backbone.js, but aren’t entirely sure what it does, how it does it, and what else is out there. Furthermore, is it worth investing time learning Backbone.js only for someone to replace it with something more cutting edge? The field is definitely changing fast – as single page applications are now commonplace, their associated techniques are cropping up on traditional websites. It’s clear that client-side development requires more investment in the architectural side of development. Organising code with mature techniques lifted from the classic Design Patterns: Elements of Reusable Object-Oriented Software is just the beginning.


The choice of frameworks is bewildering. TodoMVC provides implementations of a to-do app in more frameworks than anyone has time to learn. Choosing the right framework for a given project is only the start of the problem, however. The real issue is learning how to use the framework correctly. It’s very easy to write “anti-patterns” with something like Backbone.js, and quickly get into a spaghetti code mess.

Choosing the right framework and using it well comes down to knowing what you need. If you’re in the position of thinking you might need a client-side MVC framework, but you’re not sure why, then my advice is to get your hands dirty. Take a look at how these frameworks are built, and what they provide. Eventually you’ll see similarities between them, and see how to apply their features to your own projects.

Forget Models and Controllers

Forget terms like models and controllers for a moment, and consider these frameworks at a higher level.

Backbone.js: Helps represent and manipulate data with JavaScript. The data originates from a server or can be generated by the browser – Backbone.js is good at synchronising data with RESTful services. Events fire when data changes, triggering code that can update the interface. It also provides some tools for generating (rendering) reusable templates based on events – however, these “views” are more of a convention than sophisticated API. URLs can be dynamically updated by the browser using the HTML5 History API.

Knockout: Uses data bindings to automatically update the interface based on changes to data. Doesn’t provide client-side routing or data synchronisation with a server.

These two frameworks are very different: Knockout focuses on automatic data binding to keep the UI in sync, and offers tools to write reusable view-oriented code to do this. Conversely, Backbone.js requires the user to manually wire up events between the interface and data, and instead makes it easier to integrate with RESTful services and create modern single page application using the routing API.

If I was writing a single page application backed by a RESTful service, I may opt for Backbone.js. However, if I was writing a more traditional web app with complex data-driven templates, then Knockout might be a better fit.

So, Which MVC Framework Should I Use?

Set aside hyperbole and stop worrying about which framework implements MVC correctly. Instead, look at each framework in relation to your project and requirements at a high level.

In the upcoming weeks I plan to further demystify MVC frameworks by exploring the patterns and anti-patterns. I’d also like to look at some of these frameworks in more depth in some upcoming code review style posts.

Node Roundup: 0.6.20, New npm Site, Raspberry/ARM, Engines Removal, nodist

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

Node 0.6.20

Node 0.6.20 has been released. The 0.6 series is now in “maintenance mode”, so this release tidies a few things and updates npm, there isn’t anything application-breaking as far as I can tell.

Node 0.8.2 was also released. There are bug fixes and incremental improvements, I’ve updated to it for all my development work and it seems fine so far.

New npm Site

The new npm site is available at The new design is based on – the navigation, icons, and typography have been reused, which makes a welcome change from the old hacker-friendly monospaced font design.

Signing in to the new site allows account credentials to be edited, including social network handles. Avatars are supported through Gravatar. And… packages have their own pages, no more hash URLs! Take a look at the Express npm page to see what I mean. It even displays documentation.

The source for the new site is open source and can be downloaded at GitHub: isaacs / npm-www. This is actually quite enlightening, because Isaac has written a readme with an extremely detailed design philosophy.

Ridiculous speed: This site should be surprisingly fast. Towards that end, things are cached and served from memory whenever possible, and ETagged for browser-cacheablility.

No lib folder: If you would put it in lib/, then it belongs in a separate module.

Considering who this comes from this could form the start of a guide to idiomatic Node web applications, which is something I feel is sorely lacking in the community.

There aren’t currently any tests, outside of the project’s dependencies. However, even if you’re a die-hard TDD advocate I still think there’s a lot to be learned from taking a deeper look at this project.

From the Groups: Raspberry Pi, Engines

Trying to build Node for a Raspberry Pi? There’s a discussion about ARM support on nodejs-dev:

Every time there’s a new version of node I have to go in and modify config files specifically for ARM and it seems that nodejs just doesn’t run very well on it.

Apparently building for ARM requires V8 to be compiled as a shared library:

The current problem is with V8 + gyp. If you compile v8 from svn as a shared library, node should then compile alright.

– AJ ONeal

I also noticed an interesting discussion about removing “engines” from package.json:

Engines is advisory. It prints a warning. Set engineStrict in your package.json, or --engine-strict config, to make it strict. (If the package.json field is abused, it will be removed eventually. I don’t suspect this is going to be an issue.)

There’s a commit related to this here: Make ‘engines’ field advisory.


nodist (License: MIT, npm: nodist) by Marcel Klehr is a Node version manager for Windows. Once Node has been installed with the standard Windows installer, other versions can be installed using nodist’s command-line interface:

nodist + v0.8.1

Typing nodist --help will display documentation for each command and examples.

jQuery Roundup: New Sizzle, HubInfo, Select2

10 Jul 2012 | By Alex Young | Comments | Tags jquery plugins selectorengines
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

The New Sizzle

In The New Sizzle, Timmy Wilson explains how jQuery’s revised CSS selector engine works. Timmy has compared it to other selector engines, and shows how the new implementation differs to the previous version.

The part about extensibility is promising:

… there are a couple changes that make Sizzle even more extensible. Now with the parser compiling a function of functions, you can receive more information when creating your custom selector. Sizzle.compile is exposed so you can cache your selectors before they get used. While compiling is still very fast without caching, you can make sure that step is skipped before the selection is ever run.


HubInfo (GitHub: jgallen23 / hubinfo, License: MIT) by Greg Allen displays a GitHub repository widget. It comes bundled with CSS, so it’s easy to get something looking good straight away with a small amount of JavaScript:

  user: 'alexyoung'
, repo: 'dailyjs'

The hubInfo method returns an object that will fire a render event. The project’s documentation shows this being used to add a Twitter share button.


Select2 (GitHub: ivaynberg / select2, License: Apache 2.0) by Igor Vaynberg is a select box replacement that features a similar style to the popular Chosen library. Unlike Chosen, the author has made Select2 work better with large data sets – results can be paginated, and infinite scrolling is supported.

There’s an active community of Select2 users at the Select2 Google Group, and there’s lots of demos and documentation on the project’s homepage.

JS101: The Function Constructor

09 Jul 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner

Last week we took a cursory glance at functions, and this week we’ll look at the Function object itself.

Creating Functions with the Function Constructor

Functions can be instantiated with zero or more arguments. The last argument is always the function body:

var sum = new Function('a', 'b', 'return a + b');
sum(1, 1);
// 2

The length property will return the number of arguments:

// 2

This property is not writeable. The function body will have access to arguments, so supporting variable arguments is still possible:

The behaviour of a function when invoked on a number of arguments other than the number specified by its length property depends on the function.

Other properties include call, apply, and bind. There’s also a toString method, which will return a string containing the function’s body. It won’t be exactly the same as the source supplied to the Function constructor.


To all intents and purposes, functions created this way are indistinguishable from any other function. There is a difference, however, and that lies in the scope binding. The Global Environment is passed as the scope for the new function, which isn’t necessarily intuitive. This isn’t a bug and is covered by the specification, but it’s worth being aware of the behaviour.

For example, this will fail because a isn’t in scope for the Function instances:

function container() {
  var a = 1
    , b = 1
    , sum = new Function('return a + b')
    , sum2 = new Function('sum()');


The amazing thing is, an eval would have access to a and b because entering eval code sets up the lexical and variable environments the usual way.

This difference is useful, because new Function offers a way to execute arbitrary code without providing access to local (perhaps considered “internal”) variables. jQuery’s JSON parser uses this distinction to parse JSON:

if (rvalidchars.test( data.replace( rvalidescape, "" )
    .replace( rvalidtokens, "]" )
    .replace( rvalidbraces, "")) ) {

  return ( new Function( "return " + data ) )();

In this way we can see eval and new Function are related, but not entirely the same. However, some well-known JavaScript professionals strongly warn against using both:

eval has aliases. Do not use the Function constructor. Do not pass strings to setTimeout or setInterval.


The Function constructor is occasionally used for metaprogramming. It’s used to generate new methods in the Mongoose MongoDB module for Node:

MongooseBuffer.prototype[method] = new Function(
  'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +
  'this._markModified();' +
  'return ret;'

In this case, it would be trivial to refactor out the Function constructor.

There are more specific cases where the Function constructor is used for more devious metaprogramming. The Jade template language compiles templates into functions. Dojo also has a few places relating to templates where it’s used as well.


The Function constructor has some scope behaviour that takes a bit of getting used to, but it’s exploited by a very specific class of libraries. In general, most code doesn’t really need to use new Function.


Bootstrap Tour, DOM Utils, asEvented

06 Jul 2012 | By Alex Young | Comments | Tags backbone.js dom events

Bootstrap Tour

Bootstrap Tour (GitHub: pushly / bootstrap-tour, License: Apache 2.0) from is a small library for building interactive product tours with Twitter Bootstrap. Tours are instances of Tour, and can contain a reference to an element to anchor to along with a title and descriptive text:

var tour = new Tour();

  element: 'selector'
, title: 'Popup Title'
, content: 'Descriptive text'

Steps will be displayed using popovers, and the tour can be ended at any time. Steps can also contain a path option so tours can span several pages.

DOM Utils

Utils (License: MIT) by Matt McDonald is a modular DOM library designed to degrade gracefully and work in a wide range of browsers. It contains a lot of the utility functions we find ourselves needing when working without a larger framework, for example:

  • Is a given object array-like?
  • Utils.node.prepend: An insertBefore wrapper method
  • Returns an array of node-like objects that match the class name

Some methods will return null in browsers that don’t support the underlying DOM API calls. This is documented thoroughly, with a suggestion on how to proceed:

Warning: this property will return null if the host environment is detected to be unsuitable; an if block or a similar construct should be used for detection.

Rather than falling over to less efficient methods, this library prefers to make the developer determine how to proceed.

Utils can be downloaded by selecting the required modules: Utils Download.


asEvented (License: MIT, npm: asEvented) by Michal Kuklis is a small event emitter module that works in Node and browsers. It works using a mixin style rather than through inheritance:

function Model() { = 0;

This gives Model methods for dealing with events, like trigger and bind.

The project has already received a few contributions, and it includes qunit tests that are easy to run in a browser.

Chrome Apps: JavaScript Desktop Development

05 Jul 2012 | By Alex Young | Comments | Tags google chrome talks videos

Evolution of Chrome Apps

June was a month of tech conferences, but it was Google I/O that really stole the thunder of E3 and Apple’s WWDC. People are understandably excited about the Nexus 7, Jelly Bean, and Chrome for iOS, but what was there for us JavaScript hackers? All of the Google I/O sessions are available for viewing, and one that caught my eye was The Next Evolution of Chrome Apps.

I saw this video referenced on Twitter by TJ Holowaychuk, and given that his JavaScript aesthetics align with mine I wanted to know why he was talking about it. It turns out there’s a lot to like about the future direction of Chrome apps and Chromebooks from a JavaScript developer’s perspective. Offline is now being taken extremely seriously – partly because existing APIs are being adapted to cope with intermittent connections, but also because Chrome apps will be integrated with the OS (whether it’s Google Chrome OS, Mac OS, Linux, or Windows). This addresses a key usability problem people have with offline web apps: how are they launched? Rather than digging around in bookmarks or Chrome’s Apps page, we’ll now be able to launch them from the OS.

After seeing this talk, here’s my hyperbolic claim: Google is going to revolutionise desktop development. Watch the talk to see if you agree.

The part of the talk that stole the show was the Arduino demo. The new APIs allow applications to access OS-level features: networking, bluetooth, and even serial IO. Mihai Parparita (Chrome Apps Tech Lead, Google Reader) demonstrated an Arduino board that controlled a motor with a potentiometer, and a Chromebook (on the latest Canary build) was able to read and write data to it.

I’ve summarised the talk below, but if you’re desperate to see sample code then take a look at the GoogleChrome GitHub account and

Breaking out of the Browser

In Breaking out of the Browser, system-level integration is discussed:

  • Launch apps from outside the browser
  • First-class OS windows – rather than just using the DOM, windows can be created that work with native controls and shortcuts (including cmd/alt-tab)
  • Full window frame without browser chrome
  • Links open in browsers, not the app

The Bizarro World Window Demo demonstrates this. This is all done with JavaScript.

Offline by Default

The Offline by Default section deals with how new packaged apps are better able to cope with offline mode or intermittent connectivity.

  • The interface and application logic are entirely local
  • There’s an enforced separation of data and UI to help prevent apps from getting into a broken state
  • An application should work without ever having connected to the network
  • Older APIs have been updated to perform better during poor connectivity
  • The fact apps launch from outside the browser helps people realise they work outside the browser and will function offline

There’s a demo of a diff tool that works differently offline. When the connection is lost, it immediately displays an offline notice and only allows local files to be opened. When it’s offline remote files can be opened instead.

New APIs

The new APIs are mainly concerned with OS-level integration.

  • System APIs: interacting with the hardware (USB/bluetooth) or OS (TCP)
  • Shared data APIs: interoperating with other apps (photos/contacts/calendar) accessed safely from multiple apps
  • (Google) Web service APIs that run well under poor network conditions: analytics, ads
  • Raw sockets, which Google employees have been using to create things like IRC clients

There’s a demo showing an Arduino board interacting with a Chromebook.

Programming Model

Of course, to facilitate all of these changes the programming model has changed somewhat:

  • Applications use a “background page” with a main event
  • The application life cycle is event-based
  • System-level signals are accessible through an event-based API
  • The APIs have bindings to more languages – Dart is mentioned, but I’m not sure what else they’ll ship with
  • Background applications can be created
  • Apps should be single page with no navigation – basically designed like desktop applications instead of web applications

There’s a bigger emphasis on the difference between extensions and apps. Extensions are now seen as something that modifies the browser itself, while apps are more like desktop applications. Some apps on the Chrome Web Store currently use extension-level functionality, but these will have to be changed to become extensions instead. I’m not sure if a package app can be distributed with an extension, because I’m sure there are some cases where the boundary is blurred – how does 1Password or LastPass fit into this model?

Security Model

The Security Model reviews Chrome’s existing sandbox approach, but also details some new features:

  • Storage isolation ensures applications can’t modify data they shouldn’t have access to
  • Applications can be restricted using a new permission system
  • There’s a new <browser> element that allows apps to render a page in a similar way to an iframe, but without the security issues

Systems Applications Working Group

It certainly seems like these changes will open up new possibilities for developers interested in targeting Chrome and Chromebooks, but doesn’t this mean we’re investing in vendor-specific technology that we can’t use elsewhere? Well, Erik and Mihai addressed this by announcing that Google is working with Mozilla, Samsung, and Intel on the System Applications Working Group:

The mission of the System Applications Working Group is to define an runtime environment, security model, and associated APIs for building Web applications that integrate with a host operating system.

They’re also in the early stages of looking at adapting this technology for mobile platforms.

Node Roundup: NodeConf Resources, ErrorBoard, Override

04 Jul 2012 | By Alex Young | Comments | Tags node modules apps express events middleware
You can send in your Node projects for review through our contact form or @dailyjs.

NodeConf Resources

This week has been all about NodeConf, and I’ve been collecting resources for those of us who can’t make it:

The Coverage of NodeConf 2012 on Lanyrd has more material. That should be enough to get your teeth into!


ErrorBoard (License: MIT) by Aziz Yuldoshev is an open source Express application that collects client-side JavaScript errors. The author has split the project up into routes and modules, rather than something that follows the popular MVC-inspired approach. It uses MongoDB, and the interface is Bootstrap-based so it’s fairly easy to modify.


Override (License: MIT, npm: override) by Oleg Podsechin is a “general purpose middleware framework” – that is, it extends the concept of middleware to processes, allowing self-contained environments to be composed that override standard behaviour.

For example, Override modules make it possible to replace the built in console.log with a version that sends the logs to a third party service, chroot the current process, enable profiling, etc.

Override modules have a signature similar to other Node middleware APIs:

module.exports = function(next) {
  console.log('Hello Override!');

The next parameter is the next function to call in the override middleware chain. Oleg also recommends distributed reusable modules through npm, and prefixing the module’s name with or- so they’re easy to find.

jQuery Roundup: 2.0, UI 1.9 Beta, Handpicked jQuery Plugins v2

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

jQuery 2.0: Dropping Support for IE6-8

Last week, Dave Methvin posted about jQuery 1.9 and beyond. jQuery 2.0, which should be released in early 2013, will remove support for IE6-8. If you’ve followed the Let’s Make a Framework posts, you’ll have learned about a lot of the special cases frameworks have to include to support older versions of Internet Explorer. In an effort to clean up jQuery and stablise the API – in fact, 2.0 should be compatible with 1.9:

Our goal is for 1.9 and 2.0 to be interchangeable as far as the API set they support. When 2.0 comes out, your decision on which version to choose should be as simple as this: If you need IE 6/7/8 support, choose 1.9; otherwise you can use either 1.9 or 2.0.

Due to the backlash (for and against) the IE support changes, Dave wrote a follow-up post: jQuery 1.9 and 2.0 - TL;DR Edition. This attempts to answer common questions asked by the community:

Why is the jQuery core team dropping support for oldIE (IE 6/7/8)? We’re not! jQuery 1.9 will support oldIE when it’s released next year. The jQuery team will continue to support and maintain version 1.9 even after jQuery 2.0 is released.

jQuery UI 1.9 Beta

jQuery UI 1.9 Beta has been announced, which includes:

  • Autocomplete accessibility updates
  • Accordion API redesign and accessibility updates
  • Tabs API redesign
  • Position API redesign

There are also new widgets, including the Spinner widget.

Handpicked jQuery Plugins v2

Handpicked jQuery Plugins (GitHub: higgo / handpicked.jquery.plugins.repo) has been updated to version 2. The collection now includes a CDN service, and features many more high-quality handpicked plugins.

JS101: Function

02 Jul 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner

We’ve already been using functions and methods (remember the difference?) as part of this series, but it’s time to take a deeper look at one of my favourite parts of the language. Prepare to have your mind blown by two incredible facts about the humble function.

Functions are Objects

The ECMAScript Language Specification defines three ways to create functions. The first is a function declaration:

function sum(a, b) {
  return a + b;

A Function object will be instantiated behind the scenes, and returned as the result of this expression. With that in mind, the following should make complete sense:

var sum = function(a, b) {
  return a + b;

The function expression results in a value being returned, and it can be assigned as required. That’s because the function’s identifier is optional, and also because a Function object is returned.

The Function constructor isn’t hidden away by the interpreter, however. It can be used like this:

var sum = new Function('a', 'b', 'return a + b');

That brings us to an important point: functions are objects. They’re not a pre-OO construct that’s used to somehow build JavaScript’s object-oriented features – they’re actually objects themselves and can be manipulated as such.

When functions are passed as arguments or set to variables, they’re colloquially known as anonymous functions. This term isn’t used within the ECMAScript specification, but you’ll see it referred to when people discuss popular APIs like jQuery:

$('selector').each(function() {
  // Inside the anonymous function passed to jQuery's `each` method


Functions can be created anywhere an expression can appear, which means they can appear inside other functions:

function sum(a, b) {
  function max() {
    return a > 100 || b > 100;

  if (max()) {
    throw new ArgumentError('Value too large');
  return a + b;

We’ve already used this when creating “private” functions inside prototype methods and constructors. However, notice how the arguments to sum are visible inside the max function. Internally, the function is passed the VariableEnvironment of the current context, which is otherwise known as the scope.

The fact these inner functions receive access to the variables in their containing function’s scope is useful, and known as a closure:

Let closure be the result of creating a new Function object as specified in 13.2 with parameters specified by FormalParameterListopt and body specified by FunctionBody. Pass in funcEnv as the Scope.


Next week we’ll look at functions in more depth.


LZF Compression, Nekoreader, Backbone.BindTo

29 Jun 2012 | By Alex Young | Comments | Tags libraries backbone.js html5 filesystem


LZFjs (GitHub: pkalogiros / LZFjs, License: GPL3) by Pantelis Kalogiros is a compression library based on LibLZF that uses the File API to compress files in client-side JavaScript:

The script is converted from the C version of LZF and works surprisingly fast and well. Both its functions (compress/decompress) accept and return an arraybuffer.

Even though it’s been converted from C, the JavaScript is surprisingly easy to follow.


Nekoreader (GitHub: nekoreader / is a client-side feed reader created by Vincent Grastic. It uses JSONP, and Google’s Feed API to handle feeds. It has an API that allows a list of feeds to be specified in a JSON file. A template file and CSS can also be supplied to style the results.

Although people have been using Google’s Feed API for a while for similar projects, I like the fact the author’s example shows how to configure an entirely client-side app using services like GitHub and Dropbox.


Radoslav Stankov’s Backbone.BindTo (License: MIT) is a Backbone.js extension that makes it easier to bind models to views. The author’s example compares standard Backbone.js code with his extension:

window.UserCardView = Backbone.View.extend({
  initialize: function() {
    this.model.bind('change:name',  this.renderName,  this);
    this.model.bind('change:email', this.renderEmail, this);
  remove: function() {
    this.model.unbind('change:name',  this.renderName,  this);
    this.model.unbind('change:email', this.renderEmail, this);
    Backbone.View.prototype.remove.apply(this, arguments);
  renderName:  function() { /* ... code ... */ },
  renderEmail: function() { /* ... code ... */ }

Using Backbone.BindTo makes this feel less like boilerplate:

window.UserCardView = Backbone.View.extend({
  bindToModel: {
    'change:name':  'renderName',
    'change:email': 'renderEmail'
  renderName:  function() { /* ... code ... */ },
  renderEmail: function() { /* ... code ... */ }

Events will be unbound when views are removed, and there’s also Backbone.BindTo.noConflict for using the extension without modifying Backbone.View.

The same author has also recently released Backbone.Handlebars, which helps integrate Backbone.js and Handlebars.js.

More ES6 Modules Reactions, Dojo 1.8 Calendar, Maria, Brackets

28 Jun 2012 | By Alex Young | Comments | Tags libraries mvc ES6 dojo apps editors

More ES6 Modules Reactions

Yesterday I mentioned Isaac Schlueter’s post about ES6 modules, and now James Burke has responded with Comments on Isaac’s ES modules post. James’ comments are interesting given his background with RequireJS, and it’s easy to see how much his thoughts are influenced by AMD.

James has also written ES Modules: suggestions for improvement, in which he states “I want AMD and RequireJS to go away”:

They solve a real problem, but ideally the language and runtime should have similar capabilities built in.

New Dojo Components

Dojo calendar

The new Dojo calendar and gauges are explored in Introducing new visualization components in Dojo 1.8. A lot of client-side developers have asked me about full-blown calendar libraries over the years, and this one looks extremely elaborate.

The calendar documentation shows off how simple the API is:

require(["dojo/parser", "dojo/ready", "dojox/calendar/Calendar"],
  function(parser, ready, Calendar){
      calendar = new Calendar({
                   dateInterval: "day",
                   style: 'position:relative;width:500px;height:500px'
                }, 'someId');

There’s also a stunning amount of documentation, with examples, diagrams, and CSS styling details.


I really love the TodoMVC project by Addy Osmani. It showcases lots of client-side MVC frameworks. However, seeing as most people seem to misinterpret what MVC means, Peter Michaux has created Maria to set the record straight:

An MVC framework for JavaScript applications. The real MVC. The Smalltalk MVC. The Gang of Four MVC.

In Maria, models are event targets that can be observed by any other objects (including views, controllers, and other models). Views observe models and represent their current state. Controllers determine what happens when users interact with views.

There’s a TodoMVC example for Maria that breaks down like this:

The view files change elements based on models, but you won’t see a fragment of HTML in them. In Maria, the concept of a view is distinct from a template. For example, TodoTemplate.js contains the list element HTML fragment.

This stricter interpretation of MVC may be beneficial because views become easier to reuse, and the event-based design seems natural in JavaScript.

Now, you’re probably not going to replace your Backbone.js projects with Maria anytime soon, but it’s definitely worth trying out Peter’s project to see how it can better inform development with your MVC-style library of choice.



Brackets (GitHub: adobe / brackets, License: MIT) from Adobe is an open source editor aimed at web developers. There’s detailed blog post all about it here: Building a Desktop-Quality App on Web Technologies.

Although it’s built with web technology, it includes a native desktop application to make working with local files easier. It seems like they’ll be working to remove this dependency in the future, and there’s always the possibility of using something like for accessing files from services like Dropbox.

Coincidentally, Cloud9 IDE has been updated with new collaboration features, compilation (gcc) and interpreter support (Ruby, Python) support, and offline editing.

Node Roundup: 0.8, ES6 Modules, Kapitalize,

27 Jun 2012 | By Alex Young | Comments | Tags node modules bitcoin images apis
You can send in your Node projects for review through our contact form or @dailyjs.

Node 0.8

Node 0.8 has been released, and Isaac Schlueter has written up a detailed post with some impressive benchmarks: Node v0.8.0. In terms of compatibility, reports from the community seem positive so far. As always, keeping an eye on the nodejs Google Group is a wise idea to gauge potential issues.

As I’ve been researching material for the Windows and Node series, I’m excited about the future of cross-platform addons:

GYP was used already in Node v0.6 to build on Windows, but now it defines the build on all platforms. Node is still in the process of migrating external addon modules to GYP, and node-gyp is included with npm. In future releases, node-waf will be officially deprecated.

The REPL has been improved – long lines now wrap correctly, and built-in modules are automatically loaded without needing a require. For example, typing net will automatically return the net module. There’s no magic to this, repl.js now defines a list of built-in modules that are automatically loaded when a command matches one.

Work has already started on 0.9, and Isaac mentions the long talked about HTTP refactoring. However, 0.6 releases will continue to the end of 2012, so don’t fret if you’re still heavily invested in 0.6.

ES6 Modules: A Simpler Proposal

The ECMAScript Modules Proposal represents a major point of contention in the JavaScript community. Frustrated at discussing it in 140 characters, Isaac Schlueter finally wrote what he really thinks of it all in On ES 6 Modules.

This isn’t politics. We’re not voting for parties. The goal is to figure out the best API, which is a complex thing. The solution space is wide, and it is naive to reduce it to a boolean prematurely.

The discussion is ongoing, but Brendan Eich responded directly here: ES Modules: suggestions for improvement

Static module systems are static, in dependency prefetching, in binding, and in export vs. import checking.


Kapitalize (License: MIT, npm: kapitalize) is a Bitcoin client that has a chainable API and supports the Bitcoin API.

var kapitalize = require('kapitalize')()

.auth('Macintyre', 'mypassword')
.set('host', '')

The module includes tests, and documentation can be found in the readme. is a new service that makes avatars easier to work with for developers. The client library (License: MIT, npm: by Vadim Demedes is a Node module that works with this service:

AvatarsIO.upload('path/to/image.jpg', function(err, url) {
  // url is a URL of just uploaded avatar

On a related note, Chute (npm: chute) by the same author is a client for Chute, which allows sets of photos to be uploaded and managed using a simple API.

jQuery Roundup: jQuery 1.8: Beta 1, AttC, DPB, Iframe Height

26 Jun 2012 | By Alex Young | Comments | Tags jquery plugins iframes graphs
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

jQuery 1.8: Beta 1

jQuery 1.8: Beta 1 is out, and there’s going to be more jQuery news to follow over the coming weeks:

There will be even more exciting jQuery news at the jQuery Conference in San Francisco later this month, with blog posts to follow.

Custom jQuery builds are now supported through Grunt. That means the ajax, css, dimensions, effects, and offset modules can be safely removed, and even replaced with another library.

In addition, the animation code has been cleaned up, and CSS transitions are supported. Interestingly, by jQuery 1.9 $.browser will be dropped:

Ever since jQuery 1.4, we’ve been evangelizing that browser detection via the user agent string is a bad idea. Yet we’ve been an enabler of bad practice by continuing to offer $.browser. As of jQuery 1.9 we’ll remove it entirely and you’ll need to use the 1.9 compat plugin.

As usual there’s a full list of changes in the blog post: jQuery 1.8: Beta 1.


AttC (License: Apache 2.0) is a jQuery plugin that converts HTML tables to graphs using the Google Visualization API.

The jQuery part is a simple method call, $(selector).attc(), but configuration is performed through the corresponding HTML using data attributes. The authors have written a guide to basic usage for AttC.


DPB (License: GPL) by Dannie Hansen is a dynamic popup plugin that supports iframes and modal popups. An overlay can be displayed that dims the page, and there are callbacks for the open and close events:

  animation: 'topSlide'
, type: 'inline'
, width: 200
, height: 100
, top: 20
, selector: $('.inlineElement')

Iframe Height

Iframe Height Jquery Plugin by Ilker Guller sets the height of an iframe based on the content, and includes a fix for cross-domain iframe resizing. The plugin is invoked with $('#autoIframe').iframeHeight, and the options available are as follows:

  resizeMaxTry: 2
, resizeWaitTime: 300
, minimumHeight: 100
, defaultHeight: 500
, heightOffset: 90
, exceptPages: ''
, debugMode: false
, visibilitybeforeload: true
, blockCrossDomain: true

JS101: Call, Apply, and Bind

25 Jun 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner

Last week we looked at this, and how it can be assigned and manipulated. The example I gave showed that a function inside another function (or method) will resolve this to the global object, and I used var self = this to reference the intended object.

Reader n1k0 pointed out another solution:

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

    function checkBounds() {
      if (this.x > 100) {
        console.error('Warning: Shape out of bounds');

The call and apply Methods

In JS101: Object.create, I mentioned how can be used to chain constructors. Let’s take a deeper look at these methods of Function.

The difference between the two is we generally use call when we know what a function’s arguments are, because they’re supplied as arguments. Conversely, apply expects an array of parameters:

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

    function checkBounds(min, max) {
      if (this.x < min || this.x > max) {
        console.error('Warning: Shape out of bounds');
    }, 0, 100);
    checkBounds.apply(this, [0, 100]);

These methods have been around since ECMAScript 3rd Edition, and you’ll see them used a lot. Take a look at the source for any popular JavaScript project and you’ll find one of these methods being used:

Why are these methods so popular? Basically it comes down to functions being a first class citizen in JavaScript. I’ve been talking about the importance of objects for weeks, but learning how to manipulate functions is the key to mastering JavaScript.

JavaScript allows us to pass functions around, then execute them in different contexts by taking advantage of call and apply.

This is an example from the beginning of jQuery’s documentation:

$('').click(function() {

Here, this refers to the relevant DOM object. We’ve supplied our own callback, but this points to something that makes sense within the context of jQuery’s API.


In the comments for the previous post, Andres Descalzo pointed out that Function.prototype.bind can also be used to change this. The bind method of Function was introduced in ECMAScript 5th Edition, and it returns a new function that’s bound to a different this:

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

    function checkBounds(min, max) {
      if (this.x < min || this.x > max) {
        console.error('Warning: Shape out of bounds');

    var checkBoundsThis = checkBounds.bind(this);
    checkBoundsThis(0, 100);

Notice that a new variable has to be created for the newly bound function. The comment Andres posted uses an anonymous function to remove the extra variable:

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

    var checkBounds = function(min, max) {
      if (this.x < min || this.x > max) {
        console.error('Warning: Shape out of bounds');

    checkBounds(0, 100);

I like Mozilla’s bind documentation, because it shows how some built-in methods like setTimeout require less syntax when used with methods. The lesson here isn’t really due to the design of setTimeout but more general: using bind is a convenient way to pass a method to another function.


When working with methods, the value of this is important. By using the apply, call, and bind methods of Function, we can:

  • Change this inside a function, enabling flexible APIs to be created as demonstrated by popular projects like jQuery, Backbone.js, and Express
  • Reduce syntactical overhead when using functions inside methods, and passing methods to other functions
  • Chain calls to constructors (see JS101: Object.create)

Jam, js-schema, Chai Plugins

22 Jun 2012 | By Alex Young | Comments | Tags libraries modules package-managers testing



Jam (GitHub: caolan / jam, npm: jamjs) by Caolan McMahon is a client-side package manager, with a focus on AMD. It can be used to download client-side libraries, and compile them for deployment. Packages will be installed to ./jam.

Usage looks like this:

$ npm install -g jamjs
$ jam install jquery
$ jam install backbone
$ ls jam
backbone          jquery            require.js
jam.json          require.config.js underscore
$ jam ls
* backbone 0.9.2
* jquery 1.7.2
  underscore 1.3.3-jam.1

Running jam compile will output a file containing selected modules and RequireJS. RequireJS can be swapped for a lightweight replacement. That means certain modules could be bundled separately so your application can load them when required, taking advantage of asynchronous resource.

Jam also supports version locking. I kept looking for a manifest file or package.json, but it’s done like this:

$ jam lock jquery@1.7.2
$ jam ls
* backbone 0.9.2
* jquery 1.7.2 [locked 1.7.2]
  underscore 1.3.3-jam.1


js-schema (License: MIT, npm: js-schema) by Gábor Molnár allows schemas to be defined using simple JavaScript, and can work with the JSON Schema format. It’ll work in Node and browsers as well. Schemas are defined in terms of nine rules, which includes things like matching regular expressions and objects.

This basic example from the readme demonstrates how it works:

var schema = require('js-schema');
// or <script src="js-schema.min.js"></script> in the browser

var Duck = schema({          // A duck
  quack: Function,           //  - can quack
  feed: Function,            //  - can be fed
  age: Number.min(0).max(5), //  - is 0 to 5 years old
  color: ['yellow', 'brown'] //  - has either yellow or brown color

Notice that this adds methods to the built-in constructors, and the author hasn’t yet included unit tests. Purists may prefer to see schema.Number, as in other validation frameworks.

Chai 1.0

Chai 1.0 (GitHub: chaijs / chai, License: MIT) was released recently. There’s been a lot of bug fixes and improvements since the 0.5.x releases, and the developers have improved the API so it’s easier to extend Chai with plugins.

The Chai Plugin Directory can be used to find plugins, and it even shows if the plugin is intended to work with Node or a browser. Each plugin page includes documentation and installation details, for example: chai-jquery.

Windows and Node: PowerShell

21 Jun 2012 | By Alex Young | Comments | Tags node tutorials windows windows-and-node
To read previous posts in this series, view the windows-and-node tag.

This article is aimed at Unix-oriented developers who are interested in learning a little bit about Windows scripting. It also demonstrates an easy way of calling PowerShell from Node.

Windows PowerShell is comprised of three parts: a command-line shell, a scripting language, and an integration layer with the .NET Framework. It supports both COM and WMI, so combined with the scripting facilities it’s a perfect tool for administrative task automation. There are quite a few Node modules that include shell scripts – PowerShell is a Windows-friendly way of achieving similar goals.

Modules that include man pages for Unix systems can support Windows by including Windows PowerShell Help, which are essentially just XML files. I’m not sure if it’s sensible to use this to document a Node program because it seems focused on PowerShell modules themselves, but it seems worth mentioning.

If you’re a Unix-based Node developer who’s looking to support Windows users, then it’s a good idea to familiarise yourself with the basics of PowerShell. PowerShell can be used to execute programs, which will run as a separate process (just like a Unix shell). .NET programs designed specifically for PowerShell are called cmdlets – these are considered “native” commands and execute within the current PowerShell process. They can actually support input and output as objects, which means collections of objects like arrays can be read and written using pipes.

Using PowerShell

Loading PowerShell

The Windows PowerShell binary itself can be found in the Start menu under All Programs, Accessories. There’s also Windows PowerShell ISE (Integrated Scripting Environment), which is an IDE for writing PowerShell scripts.

Once it’s loaded, you can try issuing some commands. The help pages I mentioned can be accessed with get-help, so try typing get-help get-service:

Loading PowerShell

Tab completion is supported, so typing Get- and pressing tab will cycle through each matching command. Completion also works for parameters.

PowerShell also features aliases to Unix commands. The Get-ChildItem cmdlet lists files and directories, much like ls in Unix. Fortunately, Get-ChildItem is aliased to ls, which makes things a little bit easier for those versed in Unix shells. There are lots of other aliases for DOS and Unix commands:

  • Get-Content: cat
  • Get-Help: man, help
  • Set-Location: cd

Using PowerShell with Node

What I’ve been building to here is how to take advantage of PowerShell’s convenience and integration with Window-specific APIs and interfaces like COM from within Node programs. This program will list the current directory using Node’s child_process module:

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

// List a directory
exec('powershell.exe -Command "Get-ChildItem"', function(err, stdout, stderr) {

The basic pattern is powershell.exe -Command "...". The result should look like this:

PowerShell from Node

Meanwhile, accessing objects using COM is also supported by PowerShell:

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

// Use COM objects to get filesystem information
script = '$f = new-object -com "scripting.filesystemobject"; $f.drives | where {$_.drivetype -eq 2} | Select Path,AvailableSpace,FreeSpace,TotalSize';

exec('powershell.exe -Command "' + script + '"', function(err, stdout, stderr) {

Where might this come in useful? Well, I have a feeling that certain modules that depend on Unix-specific binaries could be ported to Windows more easily by using PowerShell. And Windows developers could use it to interface with native services without building native addons.


  • PowerShell is a command-line shell, scripting language, and integration layer with .NET
  • It supports help files and is extensible
  • Commands often work with objects rather than text, and objects can be pipelined
  • Forking using the PowerShell binary is possible, which may help port modules that depend on Unix binaries

Node Roundup: 0.7.12, nd, futoncli

20 Jun 2012 | By Alex Young | Comments | Tags node modules couchdb databases documentation
You can send in your Node projects for review through our contact form or @dailyjs.

Node 0.7.12: Prepare for 0.8!

Node 0.7.12 is here, and Isaac Schlueter said Node 0.8.0 will be released later this week:

Please try out this release. There will be very virtually no changes between this and the v0.8.x release family. This is the last chance to comment before it is locked down for stability. The API is effectively frozen now.

That means it’s crunch time! Efforts have been made to preserve support for binary addons that use libeio and libev, but libev will be officially deprecated in 0.8 and gone in 0.9.

The 0.6 era feels like halcyon days – a time when Node received a huge amount of attention from the mainstream technology press, and stronger than ever developer interest. I’d like to wish the core team the best of luck with the 0.8 release.


Back in April, TJ Holowaychuk released mad(1), an alternative manual page system based on Markdown. Now Russ Frank has released nd (License: MIT, npm: nd), which is similar to mad but focused on displaying documentation for npm modules and is written in JavaScript.

Typing nd module will display the documentation associated with module. The project’s readme contains lots of tips for finding documentation within modules and displaying it, and it also points out that it supports Windows – it’ll run fine in the standard cmd.exe command interpreter.



If you’re working with CouchDB, then futoncli (License: Apache 2.0, npm: futon) by Nuno Job may be useful. It’s a command-line tool for managing CouchDB, and is based on the author’s nano database driver.

Once installed, the futon binary will accept commands, and configuration can be persisted to the ~/.futoncliconf file. The author has made a video of futoncli to demonstrate the main features.

jQuery Roundup: Bootstrap Extensions, IndexedDB Polyfill, Backbone UI

19 Jun 2012 | By Alex Young | Comments | Tags jquery plugins backbone.js bootstrap databases indexeddb
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

Nijiko’s Bootstrap Extensions

Nijiko Yonskai sent us two new Bootstrap extensions: Notifications (GitHub: Nijikokun / bootstrap-notify, License: Apache 2.0) and Toggle Switches (GitHub: Nijikokun / bootstrap-toggle, License: Apache 2.0).

The Notifications extension uses the same look and feel as Bootstrap’s built-in alerts, but displays them as popups instead. It works like a typical jQuery plugin:

  message: { text: 'Here is a simple message' },
  type: 'success'
}).show(); // for the ones that aren't closable and don't fade out there is a .close() function.

The Toggle Switches extension turns checkboxes into a larger more graphical switch that looks a bit like the iOS UISwitch. The author has included the required CSS as well.

IndexedDB Polyfill

The current state of client-side databases is confusing, mainly because there are major browsers that still don’t support IndexedDB. However, the IndexedDB Polyfill (GitHub: axemclion / IndexedDBShim, License: GPL2/BSD) by Parashuram Narasimhan allows browsers that still support Web SQL Database to use Indexed Database API instead. It also works with the author’s JQuery IndexedDB Plugin.

Including this polyfill on a page allows applications to use window.indexedDB as a single point into the IndexedDB API. The author has written some additional material about the plugin on his blog:

Backbone UI

Backbone UI (GitHub: perka / backbone-ui, License: MIT) by Joe Stelmach allows Backbone models and collections to be displayed as UI components. By using data binding, the UI is kept up-to-date, and it’s pretty easy to change the components using CSS.

The authors have attempted to make it work more closely with the DOM rather than using HTML templates. This is possible in part due to Joe’s Laconic library. The focus is on JavaScript-heavy client-side applications rather than traditional server-side generated templates.

The documentation includes a sample to-do list application, and the source is surprisingly easy to follow and concise.

JS101: this

18 Jun 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner

So far in JS101, our examples have mentioned this and functions that take advantage of its behaviour, like Function.prototype.apply and However, before approaching other aspects of the language, we should first address this and execution contexts.

Methods and Functions

In this article I refer to both methods and functions. Method is defined in the ECMAScript specification as follows:

… function that is the value of a property.

NOTE When a function is called as a method of an object, the object is passed to the function as its this value.

We typically think of functions as a standalone subroutine, while methods are properties of an object that happen to be functions. This nomenclature is used widely within the community.

Execution Context

According to the ECMAScript 5.1 specification, an executing program is formed of “execution contexts”. These execution contexts support the language constructs we need to manage scope – the visibility of variables and function declarations from other parts of a program.

The execution context contains references to various elements that enable state within a program to be managed according to the current logical scope – for the exact details, see Execution Contexts in the specification. What we’re interested in is how the current value of this is determined.

Global Context and Constructors

Try running the following code in Node or a browser:

function add(x, y) {
  return x + y;

add(1, 1);

The second line will cause the global context to be displayed: global in Node, or window in a browser. If I inserted 'use strict' after the line that reads function add..., then this would be undefined instead.

Now consider what happens when a constructor is executed:

function Shape() {
  this.x = 0;
  this.y = 0;

var shape = new Shape();

When control enters the Shape constructor as a result of new Shape(), the this value will refer to the current object. Keep this in mind when writing object-oriented code: if a function is called as a method on an object, or by using new, then the value of this will be the current instance of the object, otherwise it will be the global context (or undefined in strict mode). The lesson here is the value of this is dependent on how a function is called.

Common Mistakes

Be careful when nesting functions inside methods. Read the following example and try to figure out the value of this inside checkBounds:

function Shape() {
  this.x = 0;
  this.y = 0;

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

    function checkBounds() {
      if (this.x > 100) {
        console.error('Warning: Shape out of bounds');


var shape = new Shape();
shape.move(101, 1);

The checkBounds function is defined inside the move method, but the console.error line will never be reached. This is because the value of this will be set to the global context, which is correct according to the specification but understandably confusing and represents a common source of bugs.

Fortunately, this is a value so we can reference it by using another variable:

Shape.prototype = {
  move: function(x, y) {
    var self = this;

    this.x += x;
    this.y += y;

    function checkBounds() {
      if (self.x > 100) {
        console.error('Warning: Shape out of bounds');


Here self now points to the ThisBinding assigned when move executes, so checkBounds will work the way we intend it to. The name self can be anything, but it’s a popular convention. It’s not a reserved word, but your editor may highlight it.


When working with this, remember the following rules:

  • It’s set based on how a function is called: new MyConstructor or myObject.method() will refer to an instance, while this inside a function refers to the global context
  • Strict mode causes this to evaluate to undefined instead of the global context inside functions
  • this can be referenced by a variable, and self is the conventionally used name

If you want to read lower-level details on this topic, start by looking at how the ECMAScript 5.1 specification defines the algorithms that are used to determine this for various situations: entering global code, executing eval code, and entering functions.

WebModular, Intravenous, Sindre's Grunt Tasks

15 Jun 2012 | By Alex Young | Comments | Tags grunt audio libraries



WebModular is a modular synthesiser built using JavaScript and the Web Audio API. It’s a bit like the Google Doogle for Robert Moog’s birthday, except it’s a bit more powerful. This synth includes a pair of VCOs, VCFs, VCAs, envelopes, LFOs, and a ring modulator. It’s also got a little mixer built-in, and a keyboard. The keyboard has CV and gate outputs.

It’s a mind-blowing piece of work, and makes me wonder if we’ll ever see the likes of the Korg and Yamaha iOS apps ported to browsers.


Intravenous (GitHub: RoyJacobs / intravenous, License: MIT, npm: intravenous) by Roy Jacobs is an inversion of control library for browsers and Node. It’s distributed as a CommonJS module, but it’ll also work with AMD and in browsers without AMD. The idea behind this library is to reduce coupling between components by using a system of containers that help manage object lifecycles and manage their relationships. Containers can be nested, which seems like it would help manage objects in single page applications.

Containers are created, then services are registered with them, then classes can be defined along with their dependencies:

var container = intravenous.create();
container.register('logger', loggerClass);
container.register('someGlobalData', { data: 'hello' });

function ExampleClass(logger, someGlobalData) {
  /* use logger here */

ExampleClass.$inject = ['logger', 'someGlobalData'];
container.register('ExampleClass', ExampleClass);

There’s a lot more to it, but the author has written detailed examples in the project’s documentation.

Sindre’s Grunt Tasks

Sindre Sorhus has been writing quite a few Grunt tasks: