Contra, jquery.onoff, jQuery 1.11.0 RC1 and 2.1.0 RC1

21 Jan 2014 | By Alex Young | Comments | Tags jquery plugins ui flow-control async

Contra

Contra

Contra (GitHub: bevacqua / contra, License: MIT, npm: contra, Bower: contra) by Nicolas Bevacqua is a flow control library, similar to async, but more suited to client-side development.

It has three sets of methods: flow control, functional, and uncategorized. The flow control methods are for executing groups of functions, like λ.waterfall(tasks, done). The functional methods are a subset of what you might expect to find in Underscore.js – λ.each and λ.filter for example. I noticed that λ.each can handle both arrays and objects, so it’s different to forEach.

Each method can be exported separately, so you could just pull in a single method if you wanted to. It has Mocha tests, and can be installed with Bower.

jquery.onoff

jquery.onoff (GitHub: timmywil / jquery.onoff, License: MIT) by Timmy Willison is a toggle switch that uses checkboxes. It supports IE 9 and above, and can be loaded with an AMD loader.

Although it’s a relatively simple project, Timmy has included tests, and a Grunt build script.

jQuery 1.11.0 RC1 and 2.1.0 RC1

jQuery 1.11.0 RC1 and 2.1.0 RC1 have been released. These releases are maintenance releases, so there aren’t any API changes.

The announcement notes that these releases should work properly with Browserify, and can be installed using npm.

A Node Interpreter for iOS

20 Jan 2014 | By Alex Young | Comments | Tags node apps iOS
Nodeapp: Node for JavaScriptCore.

Back in December I wrote about Nodelike, which aims to bring Node to iOS 7 and Mac OS X through JavaScriptCore. The iOS app has now been released as Node - JavaScript Interpreter, which you can download from the App Store. You can also view the source at node-app / Interpreter.

The app itself is currently quite simple. You can load most of the core modules, like assert, events, and net, but executing code removes it from the editor. It’s literally an interpreter – a GUI REPL, rather than a way to write Node on the go.

It includes browsable documentation, so you could use it to verify ideas, or more importantly to help you learn Node. It has a lot of potential as a learning tool – combined with an eBook it would be a great way to execute examples on an iOS device, particularly as you could tweak the code to figure it out.

Interpreters in iOS. Now I've seen everything.

This would also let people take back those wasted commuter hours. Rather than playing Candy Crush Saga you could boost your Node skills!

Cerebro, Snowmen War, Cube Game

17 Jan 2014 | By Alex Young | Comments | Tags webgl games google

Cerebro

Cerebro

Cerebro is a WebGL visualisation of Google Analytics data, created by Vetrenko Maxim. You can use the author’s Google Analytics data, or your own – the project isn’t open source, so I decided to use the sample data.

It supports Leap Motion input, and uses three.js, sparks.js, and dancer.js for audio. I couldn’t get it working in Firefox, but it worked in Chrome.

Snowmen War

Snowmen War

Snowmen War (License: CC BY-NC 3.0) by Tanguy Sauvin and Claire Thibault is a WebGL game with some pretty extreme text. When the game starts, you’re warned that “THEY WILL KILL YOU”, and if you’re hit too many times the game over screen simply states “YOU’RE DEAD.” It’s blunt, which is amusing next to the slightly surreal snowmen in outer space visuals.

If you view the project’s source you can see the game engine, which uses Cannon.js, and plenty of Mr.doob’s libraries.

Cube Game

Cube Game

Mark Vasilkov wanted to make something with Goo Engine, so he came up with Cube Game. His advice is to mash the spacebar repeatedly until you win, but I found it was more playable when I realised it’s possible to slide under some of tile-like blocks.

Declarative Graphics

16 Jan 2014 | By Alex Young | Comments | Tags graphics animations reactive svg

Whenever I hear the term ‘reactive’, I immediately think about data-driven forms and widgets. Markup isn’t just used for HTML forms and widgets, however: SVG is a markup language, so why not use reactive programming techniques to generate data-driven graphics?

That’s the goal of Paths.js (GitHub: andreaferretti / paths-js, License: Apache 2.0, bower: paths-js), by Andrea Ferretti. It features a chainable API for generating SVG paths:

var path = Path()
  .moveto(10, 20)
  .lineto(30, 50)
  .lineto(25, 28)
  .qcurveto(27, 30, 32, 27)
  .closepath();

Calling path.print() returns the relevant markup. This can then be used with a templating language like Handlebars or mustache.js: templates/line.html.

This example is from the Paths.js demo (GitHub: andreaferretti / paths-js-demo). The demo uses Ractive.js to bind JSON data to UI controls and charts. It has several graphs with animations, and uses instances of Ractive together with instances of Path to create a clean, interactive data-driven UI.

Reactive Pokémon stats.

I like the combination of modern templating languages, SVG, and Ractive.js in Andrea’s demo. The Paths.js API makes generating SVG less tedious than it could be, and various charts are included that you can use to get started quickly.

If you like the sound of Ractive.js, then take a look at the Ractive.js demos, which include some SVG examples.

Node Roundup: TJ Fontaine Takes Over, Conductance, Easymongo, Schema-Inspector

15 Jan 2014 | By Alex Young | Comments | Tags node modules frameworks mongodb schema

The Next Phase of Node.js

In The Next Phase of Node.js, Isaac Z. Schlueter has announced that TJ Fontaine is now the Node project lead:

Anyone who’s been close to the core project knows that he’s been effectively leading the project for a while now, so we’re making it official. Effective immediately, TJ Fontaine is the Node.js project lead. I will remain a Node core committer, and expect to continue to contribute to the project in that role. My primary focus, however, will be npm.

Isaac also said he’s founding npm, Inc., to allow him to focus on npm and develop related products:

I’ll be sharing many more details soon about exactly how this is going to work, and what we’ll be offering. For now, suffice it to say that everything currently free will remain free, and everything currently flaky will get less flaky. Pursuing new revenue is how we can keep providing the npm registry service in a long-term sustainable way, and it has to be done very carefully so that we don’t damage what we’ve all built together.

Recently, there was an initiative by Nodejitsu to drive support and funding for npm, resulting in over $300,000 being raised. It’ll be interesting to see how this all ties together over the next year.

Congratulations and good luck to TJ Fontaine!

Conductance

Conductance

Conductance (GitHub: onilabs / conductance, License: GPL, npm: conductance) from Oni Labs is a web application server with a UI toolkit and a module system that’s compatible with client-side code.

It’s built on Stratified JavaScript, by the same company, which adds new language primitives for block lambdas, destructuring data, arrow function syntax, and more.

Conductance already has a detailed tutorial, and there’s an API guide as well.

Easymongo

Easymongo (GitHub: meritt / easymongo, License: MIT, npm: easymongo) by Alexey Simonenko is a wrapper around the native Node MongoDB driver. It has a clean, idiomatic API, and relies on plain old objects instead of models.

It has Mocha tests, and the API is documented in the readme. Basic use looks like this:

var options = {
  dbname: 'test'
};

var mongo = new require('easymongo')(options);
var users = mongo.collection('users');

var data = { name: 'Alexey', surname: 'Simonenko', url: 'http://simonenko.su' };
users.save(data, function(error, results) {
  // Returns a new document (array).
  console.log(results);
});

users.find({ name: 'Alexey' }, { limit: 1 }, function(error, results) {
  // Always return array of documents.
  console.log(results);
});

Schema-Inspector

What do you do when you’re using simple objects without an ORM layer? You use schemas to validate your user input! Schema-Inspector (GitHub: Atinux / schema-inspector, License: MIT, npm: schema-inspector, Bower: schema-inspector) by Sebastien Chopin is a JavaScript object validator that works in browsers and Node.

Given a suitable schema, you can validate objects like this: inspector.validate(schema, candidate). It can also be called asynchronously, which allows you to report issues with this.report inside functions in the schema.

It has tests written with Mocha, and a healthy amount of API documentation in the readme.

The State of jQuery, jQuery.whenLive, jTableScroll

14 Jan 2014 | By Alex Young | Comments | Tags jquery plugins

The State of jQuery 2014

The State of jQuery 2014 was posted to the jQuery blog yesterday by Dave Methvin. It basically covers jQuery’s growth through 2013, and includes a comment about how jQuery shouldn’t just be used for routing around broken DOM APIs:

People should be continuing to use jQuery because it’s a powerful way to implement designs and provides a vibrant ecosystem of useful plugins, not because the native DOM APIs are broken, verbose, or inconsistent. That’s why we participate in the standards process through bodies such as the W3C and ECMA.

jQuery.whenLive

jQuery.whenLive (GitHub: tkambler / whenLive, License: MIT, Bower: tkambler/whenLive) by Tim Ambler allows you to track when elements are inserted into the DOM tree, with a focus on performance:

When supported, $.whenLive leverages the browser’s MutationObserver notification system. In the event that Mutation Observers are unavailable, $.whenLive leverages the relatively new requestAnimationFrame function.

This seems like a clever way of deferring behaviour until potentially complex components are ready.

jTableScroll

jTableScroll (GitHub: mike-allison / jTableScroll, License: MIT) by Mike Allison is a plugin for adding scrollbars to tables, and it retains static headers and footers.

It calculates the width and height then wraps parts of the table in divs, applying the necessary overflow styles based on size options: $('#tableToScroll').jTableScroll({ width: 300, height: 300 }).

The header and footer are cloned and moved by looking for the thead and tbody elements, so you’ll need a well-structured table. It can be installed with nuget.

jide.js, Matchmedia-ng

13 Jan 2014 | By Alex Young | Comments | Tags angularjs ui matchMedia

jide.js

jide.js (GitHub: jidesoft / jidejs, License: MIT) from JIDE Software is a toolkit for HTML5 UI controls. The authors have embraced RequireJS, and the API is based around constructor functions that accept objects. Properties and values are observable, so UI components can react to data model changes. Layouts are also supported, which are stackable panes reminiscent of desktop UI toolkits.

There are tutorials for using jide.js with Bower and Yeoman, so if you want to create a quick project you can type npm install -g generator-jidejs and then yo jidejs.

Here’s an example of how to create a button with jide.js:

require([
  'jidejs/ui/control/Button'
], function(Button) {
  new Button({
    // define the text property
    text: 'Click the button',
    // define event listeners
    on: {
      // the 'action' event is fired when the button is clicked
      action: function() {
        alert('Hello jide.js');
      }
    }
  });
});

Matchmedia-ng

Matchmedia-ng (GitHub: AnalogJ / matchmedia-ng, License: MIT) by Jason Kulatunga is a set of AngularJS bindings for window.matchMedia. That means you can easily branch on mobile devices, or for printed content:

matchmedia.on('tv and (min-width: 700px) and (orientation: landscape)', function(mediaQueryList) {
  console.log(mediaQueryList.matches);
});

There’s also a matchMedia polyfill written by Paul Irish.

WebGL Spaceship Tutorial, Voxel Mars, particle-excess-demo

10 Jan 2014 | By Alex Young | Comments | Tags webgl tutorials graphics space science

WebGL Spaceship Tutorial

WebGL Spaceship Tutorial

Jerome Etienne shared Game Workshop: Let’s Do a Fighting Spaceship Minigame Together – a talk about building a little game with three.js and the Web Audio API. It includes slides, a video of the talk, and a demo.

Voxel Mars

Voxel Mars

Voxel Mars (GitHub: rachel-carvalho / voxel-mars, License: MIT) by Rachel Carvalho uses NASA data to generate Martian terrain, allowing you to run around a WebGL version of Mars.

As you move it displays your position on a map, and also shows the longitude and latitude. Therefore, your challenge (should you choose to accept it), is to get to the top of Olympus Mons!

The rendering style makes it look a little bit like Minecraft, and one of the author’s ideas sounds like an amazingly interesting take on that genre:

a science-based (no dragons) survival mode on which you have to generate your oxygen and fuel, extract your water, grow your food, make martian bricks, etc

particle-excess-demo

Particle Excess

Hugh Kennedy sent in particle-excess-demo (GitHub: hughsk / particle-excess-demo, License: MIT):

The particle simulation is running on the GPU to handle 262,144 particles in real time. It’s a pretty standard technique these days, but it could be helpful as a reference for some. No three.js, just modules.

If you look at the source you’ll see how shaders can be used to create interesting particle effects.

Is Koa the Future of Node Frameworks?

09 Jan 2014 | By Alex Young | Comments | Tags node modules es6

Are you tired of callback wrangling for web middleware? Koa (GitHub: koajs / koa, License: MIT, npm: koa) is a new web framework by TJ Holowaychuk, Jonathan Ong, and Julian Gruber that embraces ES6 generators down to the core. Gone is the next parameter in Express, replaced by yield next which can be called in a synchronous style.

With generators we can achieve “true” middleware. Contrasting Connect’s implementation which simply passes control through series of functions until one returns, Koa yields “downstream”, then control flows back “upstream”.

You’ll need Node 0.11.9 or above to use Koa, and the node command must be invoked with the --harmony flag. The use of generators is partly enhanced by TJ’s Co module, so if you’re not intimately familiar with ES6 promises be aware that Co is used.

Here’s an example: the app.callback method returns a handler that is compatible with Node’s http.createServer method, and uses co:

app.callback = function(){
  var mw = [respond].concat(this.middleware);
  var gen = compose(mw);
  var fn = co(gen);
  var self = this;

  return function(req, res){
    var ctx = self.createContext(req, res);
    onSocketError(ctx, ctx.onerror);
    fn.call(ctx, ctx.onerror);
  }
};

This example is from Koa’s source, and allows the following to work:

var koa = require('koa');
var app = koa();
app.listen(3000);

// Equivalent: http.createServer(app.callback()).listen(3000);

The Request Response Pattern

The key to making solid Node web applications is to realise and exploit the fact Node speaks HTTP. Contrast this to PHP or ASP, where “pages” execute and generate output. Those req and res objects are there for a reason: Express and similar frameworks are built on Node’s http core module, and the http module’s API is based around these request and response objects.

I like thinking in terms of HTTP requests and responses – it gives me the sense that I’m dealing with HTTP “functions” that take input and transform somehow. That makes it easier for me to test my web apps, and I’ve been comfortable working this way since I discovered Express.

In Koa things are slightly different:

A Koa Context encapsulates node’s request and response objects into a single object which provides many helpful methods for writing web applications and APIs.

While it’s true that Express decorates the request and response objects, Koa goes further by abstracting them. You can still get at the request and response, and there’s also a Koa request and response as well:

app.use(function *(){
  this; // is the Context
  this.request; // is a koa Request
  this.response; // is a koa Response
  this.req; // Node's request
  this.res; // Node's response
});

Notice that this is significant – you may have seen something similar in jQuery callbacks. I think it was clever of Koa’s authors to execute middleware from within a “context”, because it makes sense semantically. The current context has aliases to commonly accessed request and response properties, so the average Koa middleware has less indirection and looks lean and clean.

Understanding Yield

I realise that the advantages of generators in middleware might not be obvious at first. The best example I can think of from Koa’s documentation is measuring response time. This example yields early, allowing the response time to be measured:

// x-response-time

app.use(function *(next){
  var start = new Date;
  yield next;
  var ms = new Date - start;
  this.set('X-Response-Time', ms + 'ms');
});

The start time is recorded, then execution is deferred to the next item of middleware in the stack with yield next. This all “unwinds” at the end of the request, so as long as the x-response-time was the first item, execution will continue after yield next. That means var ms = new Date - start; will correctly measure the elapsed time.

I think many of us have struggled to stack middleware in meaningful ways, and this could make our code more readable. Think about it like this: a single function can encapsulate the entire intent of the middleware.

Future

It might be that the dependence on Node 0.11 and our investment in existing frameworks will hold back Koa’s adoption. However, remember that you can mount entire applications as middleware in Connect, so what’s to stop you from mounting a Koa app inside your existing Express apps, once generators are standard in your production version of Node?

Even if you don’t switch to Koa, you should start thinking about how to use generators, and I think middleware is a sensible place to explore their implications.

Node Roundup: Faucet, Node Compiler, Tumblr

08 Jan 2014 | By Alex Young | Comments | Tags node modules testing tap

Faucet

Faucet (GitHub: substack / faucet, License: MIT, npm: faucet) by Substack is a human-readable TAP summariser. You can pipe TAP text into the faucet command-line script, and it’ll generate prettier yet concise output.

If you type faucet, JavaScript files in test/ will be executed using tape and then automatically piped through faucet.

Substack has created some nice animated gifs that show what the results look like under various conditions. One of them even shows Mocha using tap through the -R tap command-line option.

Node Compiler

Node Compiler

Sonny Lazuardi sent in Node Compiler (GitHub: sonnylazuardi / node-compiler, License: MIT), a web-based tool for building C++. It uses g++ with execSync, wrapped up with an Express-based API.

The web interface uses the Ace editor, which supports traditional editor features like syntax highlighting. I think it’s quite an audacious idea, but it might be a little dangerous to leave on public servers.

Tumblr

node-tumblr (GitHub: meritt / node-tumblr, npm: tumblr) by Alexey Simonenko is a Tumblr API wrapper for Node. It supports OAuth, and allows you to query posts, links, answers, and the other resources Tumblr provides.

Gulp, bLazy, grunt-bowercopy

07 Jan 2014 | By Alex Young | Comments | Tags bower grunt build images node modules

Gulp

Gulp

Last night I was reading a post about Gulp by Martin Genev. Martin traces the appearance of Gulp into the JavaScript community, through GitHub comments and Tweets.

Apparently Gulp is a new build system made by Fractal, a Node consultancy with several popular Node modules under their collective belts.

Gulp is built around streams, so it feels more like idiomatic Node. You can pipe files through processors, so if you had a set of LESS files you could convert them into CSS with something like gulp.src('less/*.less').pipe(less()).pipe(minify()).pipe(gulp.dest('styles/screen.css')). It supports tasks as a unit of work, and tasks can have names and dependencies.

The project has 13 contributors already – most of the work is by Eric Schoffstall who you’ll see all over Fractal’s other projects. It has tests written with Mocha, and some decent documentation already.

bLazy

bLazy (GitHub: dinbror / blazy) by Bjoern Klinggaard is a lazy loading image script. It doesn’t have any dependencies, and supports callbacks for loading failures:

var bLazy = new Blazy({
  success: function(ele) {
  },
  error: function(ele, msg) {
    if (msg === 'missing') {
      // Data-src is missing
    } else if (msg === 'invalid') {
      // Data-src is invalid
    }
  }
});

There’s a blog post about bLazy that documents the full API.

grunt-bowercopy

I seem to waste a lot of time detangling Bower dependencies to make my client-side builds more efficient. Timmy Willison may have solved this with grunt-bowercopy (GitHub: timmywil / grunt-bowercopy, License: MIT). It allows you to specify where dependencies should go, and can reduce the amount of duplication when creating builds.

It looks like it works the way I expect Bower dependency management to work in Grunt, so I’m going to go back and look at my Grunt/Bower projects to see if I can clean then up with this.

Lukis, Backbone.Controller, lrDragNDrop

06 Jan 2014 | By Alex Young | Comments | Tags node modules testing types

Lukis

Lukis (GitHub: keripix / lukis, License: MIT) by Keripix is an experimental image editor, built with Twitter’s Flight and Fabric.js.

It’s event driven, so each main drawing component is nicely decoupled. This is based on Flight’s API, where behavior is mapped to DOM nodes.

Backbone.Controller

Backbone.Controller (GitHub: artyomtrityak / backbone.controller, License: MIT) by Artyom Trityak is a Backbone controller that supports declarative routes. It makes Backbone feel more like traditional MVC, which may appeal to you if you’re brainwashed by other MVC frameworks.

Artyom has included some documentation showing how to bind routes using Backbone.Controller.extend, and there’s also a RequireJS AMD snippet so you can get started quickly.

lrDragNDrop

lrDragNDrop (GitHub: lorenzofox3 / lrDragNDrop, License: MIT) by Laurent Renard is an AngularJS module for managing collections of items using drag and drop.

You can use it as a directive, and load it with angular.module('myApp',['lrDragNdrop']). Items can be dragged from one collection to another, copied, and sorted.

Orbit Viewer, Earhorn

03 Jan 2014 | By Alex Young | Comments | Tags webgl space instrumentation debugging

Orbit Viewer

Orbit Viewer

Orbit Viewer is a Chrome Experiment by Kevin Gill that helps visualise the orbits of comets and satellites. You can watch the famous comet Shoemaker–Levy 9, or see the current position of the International Space Station. It should work with most WebGL capable browsers.

A sort of “Where are they now” for spacecraft and comets: Check out realtime positions, along with historical and projected flight paths of our solar system’s trailblazing spacecraft and comets. All in a zoomable/rotatable 3D interface. Using historical and real-time trajectory information for NASA’s JPL Horizons system, and in-browser WebGL and Three.js rendering.

Earhorn

Earhorn (GitHub: omphalos / earhorn, License: MIT) by “omphalos” is a library for instrumenting JavaScript. You pass earhorn$ a label and a function, and then you can view the function as the values change.

The mouse example shows how this works: the source for a jQuery mousemove listener is displayed, and whenever you move the mouse the integer values for the current coordinates will be reflected in real time.

An iframe is used that loads the earhorn/index.html page which knows how to display an instrumented version of the function. Internally, Earhorn uses Esprima to generate an abstract syntax tree that is manipulated to allow the code to be observed.

It reminds me a little bit of the Watches feature in Light Table, and some of the recent improvements to WebKit Inspector.

Recipe for Express Configuration Files

02 Jan 2014 | By Alex Young | Comments | Tags node express configuration recipes

Express has a few helper methods that support configuration. There are three pairs of methods: get and set for setting values, enable and disable for toggling boolean options, and enabled and disabled for testing boolean options. Options can be set based on the current environment by using the configure method.

Here’s an example of these methods:

var express = require('express');
var app = express();
var assert = require('assert');

app.set('title', 'DailyJS');
assert.equal(app.get('title'), 'DailyJS');

app.configure('production', 'staging', function() {
  // 'emails' is an internal setting I've made up
  // It could be used to only send emails from certain environments
  app.enable('emails');
  assert(app.enabled('emails'));
});

app.configure('test', function() {
  app.disable('emails');
  assert(app.disabled('emails'));
});

The configure method is based on process.env.NODE_ENV, which is available in app.get('env'). If you access it through app.get you’ll see a default of 'development' rather than undefined. When you deploy your application you’ll want to make sure the NODE_ENV environmental variable is set to staging or production. How this is done is based on operating system or cloud provider – with Heroku it would be heroku config:add NODE_ENV=production.

These methods are useful, but sometimes you want to store settings in configuration files. It depends on the type of project you’re working on, but most of the commercial projects I’ve worked on required configuration files.

I use JSON as the format for these files because it’s easy to write and parse in Node projects. You don’t even need to use JSON.parse, you can just use require. I like to use a configuration file for each environment, so I usually end up with a directory like this:

config/development.json
config/production.json
config/test.json

You can load one of these files with require('config/development.json'), but you can go a step further by using an index.js file:

module.exports = {
  development: require('./development.json'),
  production: require('./production.json'),
  test: require('./test.json')
};

Now you can use var config = require('./config') elsewhere in your project. However, because process.env.NODE_ENV gets set, we can simplify that index.js file even further:

module.exports = require('./' + (process.env.NODE_ENV || 'development') + '.json');

Now require('./config') will return an object that contains the configuration for the current environment. I use this to do things like turn off AWS emails in my unit tests, but leave them on for the production system. By exploiting the design of Node’s module system you basically get configuration files for free.

This might not be the best solution for every project. The config module by Loren West supports YAML files, and nconf from flatiron is hierarchical – settings can be passed in as command-line options, from the environment, or from a file, and used based on precedence. It can also store settings in databases like Redis.

How do you configure your Express projects?

Node Roundup: 0.11.10, Ducky, Test-driving a Node.JS API

01 Jan 2014 | By Alex Young | Comments | Tags node modules testing types

Node 0.11.10

Node 0.11 is now pushing double figures. The three main dependencies have been updated (http_parser, uv, v8), and the core modules have a lot of fixes.

Ducky

Ducky (GitHub: rse / ducky, License: MIT, npm: ducky) by Ralf S. Engelschall is a library for querying and validating objects.

The ducky.select method accepts an object and a “path” – this path is based on dot notation. The ducky.validate method accepts an object and a string representation of its types. The validation syntax is based on JSON with some regular expression hints.

Ralf has included tests based on Chai, and you can also use this module in client-side projects.

Test-driving a Node.JS API

Test-driving a Node.JS API by Joris Ooms is a blog post about setting up a test-driven project based on Express, SuperTest, and Mocha.

At the end he says:

Often, routes are locked behind authentication (with, for example, PassportJS). We can test these just as easily with supertest, through its lower-level module superagent. I will cover this in a future blog post.

I think he’s going to talk about the technique I use for testing my web applications, where authentication is handled with SuperAgent and cookies. It’s a bit awkward to set up, so it’ll be interesting to see what he says.

AngularJS Roundup: ngDialog.js, ocLazyLoad, angular-validation

31 Dec 2013 | By Alex Young | Comments | Tags angularjs validation CoffeeScript modal ui

People keep sending me AngularJS scripts to write about, so I’ve collected a few together to start a probably infrequent AngularJS Roundup. This week we’ve got three scripts to talk about, and the first is ngDialog.js.

ngDialog.js

ngDialog.js (GitHub: likeastore / ngDialog, License: MIT) by Dmitri Voronianski is a modal dialog and popover provider. You can load it and display a dialog like this:

var app = angular.module('exampleApp', ['ngDialog']);

app.controller('MainCtrl', function($scope, ngDialog) {
  $scope.clickToOpen = function () {
    ngDialog.open({ template: 'popupTmpl.html' });
  };
});

The markup for the dialog can be a string, or loaded from a template:

<script type="text/ng-template" id="templateId">
  <h1>Template heading</h1>
  <p>Content goes here</p>
</script>

You can even use the ng-dialog directive. The project comes with two default themes, and you can use one of those to get started creating your own. The default theme has CSS animations and media queries.

ocLazyLoad

ocLazyLoad (GitHub: ocombe / ocLazyLoad) by Olivier Combe is a module for lazy loading dependencies in AngularJS. It’s a service provider that allows you to load files with promises, like this:

$ocLazyLoad.load({
  name: 'TestModule',
  files: ['testModule.js']
}).then(function() {
  console.log('done');
});

The blog post explains how the whole thing works, with detailed examples and explanations of how AngularJS loads modules.

Since the modules can only be loaded on startup and the application can only be launched using the ng-app directive, if we can find the app module, we can get the complete list of all loaded modules and dependencies.

Angular Validation

Angular Validation (GitHub: huei90 / angular-validation) by Huei Tan is a set of form validation directives. It supports various validation methods – watch, blur, or submit, so you can show errors when it makes sense for your application.

It has some built in validation types, but you can add your own in JavaScript by loading the validation provider, and then adding new validation “expressions”. Expressions are loaded based on the validator attribute. The readme has an example of how to do this, with the huei validator.

AngularJS with CoffeeScript

Finally, Elad Ossadon sent in an article about making AngularJS classes work better with CoffeeScript: Angular.js CoffeeScript Controller Base Class.

It’s a fairly short post with a base class snippet and an example controller module.

Mean, Survey Visualisations

30 Dec 2013 | By Alex Young | Comments | Tags express node mean survey

Mean

You want to build a web application, and you need a database. You can write JavaScript, but you’re not yet completely comfortable with Node. What do you do?

I wrote about Getting MEAN recently, a book about building web applications with MongoDB and Express. If you’re interested in this approach, a quick way to get started is Mean (GitHub: linnovate / mean, License: MIT), a module that collects everything you need together. It even includes AngularJS and Bootstrap, so you get a solid interface out of the box.

If you already understand the MVC pattern, and use AngularJS, then this is definitely a quick way to get started. It’s also a handy way of getting experiments up and running quickly, which is a great way to learn.

Survey Visualisations

Survey Visualisations

Konrad Dzwinel sent in these visualisations of the DailyJS survey. It allows you to see how answers to one question map to another. This is cool because I wanted to compare “What type of JavaScript do you write?” to “Where do you use JavaScript?” – I was expecting to see a lot of people writing side projects for the server at home, but the split is pretty even.

The visualisations are powered by D3.js, and Bootstrap has been used as well.

JavaScript MESS and the Internet Archive

27 Dec 2013 | By Alex Young | Comments | Tags games emulators emscripten

Atari 2600

if you program and want any longevity to your work, make a game. all else recycles, but people rewrite architectures to keep games alive. – Why the Lucky Stiff

Archive.org has a section dedicated to software. Inside you’ll find The Internet Archive Console Living Room, which has details on some major games consoles from the late 70s and 1980s, including the Atari 2600 and the ColecoVision.

The great thing about this project is they’re trying to keep old software alive. You can browse through titles and play them in a browser. This is powered by jsmess (GitHub: jsmess / jsmess), an Emscripten-based emulator derived from MESS:

The JAVASCRIPT MESS project is a porting of the MESS emulator, a program that emulates hundreds of machine types, into the JavaScript language. The MESS program can emulate (or begin to emulate) a majority of home computers, and continues to be improved frequently. By porting this program into the standardized and cross-platform JavaScript language, it will be possible to turn computer history and experience into the same embeddable object as movies, documents, and audio.

Running a game binary requires a suitable BIOS, but the groundwork for lots of systems has been added to MESS:

MESS and MAME were started over a decade ago to provide ubiquitous, universal emulation of arcade/gaming machines (MAME) and general computer hardware (MESS). While specific emulation implementations exist that do specific machines better than MAME/MESS, no other project has the comprehensiveness and modularity. Modifications are consistently coming in, and emulation breadth and quality increases over time. In the case of MAME, pages exist listing machines it does not emulate.

Over the last two years there’s been a flood of new browser-based emulators, supporting everything from the Amiga to the Game Boy Advance. Part of what makes these project possible is recent technologies like Canvas, WebGL, WebAudio, and FileReader. But even seemingly less buzzwordy APIs like typed arrays can help get old games running smoothly.

Node Roundup: 0.10.24, irc-message-stream, 100% Uptime

26 Dec 2013 | By Alex Young | Comments | Tags node modules security talks slides irc

Node 0.10.24 Released

Node 0.10.24 was released soon after 0.10.23. It updates uv and npm, but presumably this release was due to CVE-2013-6639 and CVE-2013-6640. These are security related patches for V8:

… allows remote attackers to cause a denial of service (out-of-bounds read) via JavaScript code that sets a variable to the value of an array element with a crafted index

If you run this example in Node 0.10.22 you should see a segfault.

var size = 0x20000;
var a = new Float64Array(size);
var training = new Float64Array(10);

function store(a, index) {
  var offset = 0x20000000;
  for (var i = 0; i < 1; i++) {
    a[index + offset] = 0xcc;
  }
}

store(training, -0x20000000);
store(training, -0x20000000 + 1);
store(training, -0x20000000);
store(training, -0x20000000 + 1);

for (var i = -0x20000000; i < -0x20000000 + size; i++) {
  store(a, i);
}

irc-message-stream

irc-message (GitHub: expr / irc-message, License: BSD 2-Clause, npm: irc-message) by Fionn Kelleher is a small parser that outputs objects based on RFC1459. The author has used it to create irc-message-stream, which is a transform stream.

That means you can take a socket connection to an IRC server and pipe it through your own stream handlers:

var net = require('net');
var MessageStream = require('irc-message-stream');
var messageStream = new MessageStream();

messageStream.on('line', function(line) {
  console.log('Raw line:', line);
});

messageStream.on('data', function(message) {
  console.log('Parsed message:', JSON.stringify(message));
});

var socket = net.connect(6667, 'irc.freenode.net');
socket.pipe(messageStream);

I think this is a great way to handle IRC in Node – taking advantage of the newer streams API seems a lot more idiomatic than other approaches that I’ve seen (and made!).

Towards 100% Uptime with Node

William sent in his slides for a talk called Towards 100% Uptime with Node. The slides cover the difficulties of handling uncaught exceptions in a cluster of Node processes, and ensuring that every request has a response, even if it’s to report an error.

One of the tips he mentions is to be able to generate errors on demand for development and staging. I do this in my tests – if critical paths are expected to throw exceptions, emit 'error' events, or return error objects to callbacks, then all of these eventualities should be hit as part of automated testing.

The Node applications I work on for my day job are hosted on Heroku, and I’ve found you have to be extremely careful with code that throws errors and causes the process to stop. Sometimes Heroku gets confused about the state of a process and won’t gracefully restart it, so a worker just hangs for an undefined amount of time. The way I stopped this was to fix all the bugs, which sounds like an obvious thing to say, but it took lots of log file archaeology. Coincidentally, Heroku’s default logging is inadequate, so you have to send logs to a syslog daemon somewhere, or a service like Loggly (which I preferred to Splunk).

2013 Recap

25 Dec 2013 | By Alex Young | Comments | Tags node

This year we saw Node 0.10 released, Bootstrap 3, and jQuery 2.0. People are getting increasingly excited about WebGL gaming, and client-side frameworks like AngularJS and Backbone.js are maturing and growing in popularity.

The highlight of 2013 for me was speaking at the Great British Node Conference. I’d been researching Node’s internals for the book I’m working on, so it felt like all that work culminated in a talk that got people thinking more about Node’s JavaScript and C++.

Over the next year I expect ECMAScript 6 to become more widely used. If you want to keep track of this standard, I find @esdiscuss to be the most digestible way to keep track of things.

Griswold

Happy holidays to everyone who reads DailyJS, and I look forward to writing more over the next year!