React Components

04 Sep 2014 | By Alex Young | Comments | Tags modules node libraries

React Components

In the Node community, frontend package managers are regarded with suspicion. I’ve worked on projects that manage client-side dependencies with both Bower and npm, and although Bower does an admirable job I often feel like I should be using npm instead. That’s mainly because I always have to add a step where client-side files are preprocessed and moved from where Bower downloads them, so it’s not really much different to accessing the same files in node_modules.

React Components (GitHub: vaffel / react-components, License: MIT) from VaffelNinja is a database of React components based on data on npm. It works by assuming React modules are tagged with react-component.

It has a few UI touches that makes it friendly and useful:

  • Searching is real time
  • The URL is dynamically updated with the search term
  • You can copy and paste the URL with the search term
  • Modules render the readme and the most useful links (GitHub, homepage)

This project is a great example of how npm can be completely appropriate for client-side modules, and also highlights how many interesting React components are being created right now.

Node Roundup: DataCollection.js, supererror, Readability

03 Sep 2014 | By Alex Young | Comments | Tags modules node libraries

DataCollection.js

DataCollection.js (GitHub: thestorefront / DataCollection.js, License: MIT, npm: data-collection) from Storefront is a library for querying data. You can use it in browsers or Node. The example in the documentation uses an array of objects, then filters them based on key/values, and some sql-like operators including max and distinct.

The authors claim it’s fast, and although I can’t confirm this it does include a feature for defining indexes for specific keys. It’s well documented and has 95.5% test coverage.

supererror

If you’ve got a project where you’re logging errors with console.error, but want to get more data like line numbers without modifying code, then you could try supererror (GitHub: nebulade/supererror, License: MIT, npm: supererror) by Johannes Zellner.

It changes console.error to include colours, line number, and stacks for Error objects.

Readability

Readability (GitHub: luin / node-readability, License: Apache 2.0, npm: node-readability) by Zihua Li turns pages into simplified Arc90-style HTML. It uses jsdom, supports more character encodings like GB2312, and converts relative URLs so images still work.

I seem to remember having issues with encodings and relative images with other Readability-derived projects, so this seems ideal.

Backbone setMatch, Smalleditor

02 Sep 2014 | By Alex Young | Comments | Tags components ui libraries angularjs

Backbone setMatch

Backbone setMatch (GitHub: joshbambrick / setMatch, License: MIT) by Joshua Bambrick allows you to match models in a collection based on attributes other than the id. This is applied whenever set is called on a collection, both explicitly and internally by Backbone.

The setMatch property can be used with arrays, so you can pass a set of names to match. If you pass it an object you can set options, including the id option which controls what happens when set is called. When it’s set to inherit and incoming models have an id, then match models in the collection will inherit that id, but using retain will keep the original value instead.

Smalleditor

Smalleditor (GitHub: jdkanani / smalleditor, License: MIT, Bower: smalleditor) by Jaynti Kanani is a WYSIWYG editor inspired by Medium. It requires AngularJS, and features revision tracking.

Deltas can be applied to revisions to get the next revision:

angular.module('smalleditorDemo', ['ngRoute', 'smalleditor'])
.controller('EditorController', ['$scope', function($scope) {
  $scope.$watch('editorApi', function(editor) {
    // Get current data model
    var baseDataModel = editor.dataModel();

    // After editing for a while get new data model
    var currentDataModel = editor.dataModel();

    // Compute delta between baseDataModel and currentDataModel
    var delta = editor.computeDelta(baseDataModel, currentDataModel);

    // Apply that delta to any revision to get next revision
    editor.applyDelta(nRevision, nDelta);
  });
}]);

The author cites MediumEditor, which is a similar project that is more focused on the UI and less on the revision tracking aspect.

Yet another alternative is the Pen Editor – the nice thing about Pen is it supports Markdown.

Linked Lists with Symbols

01 Sep 2014 | By Alex Young | Comments | Tags node symbol es6

LiLL (GitHub: BlackDice / lill, License: MIT, npm: lill) is a linked list implementation that uses the ECMAScript 6 Symbol API. Because Symbol isn’t widely implemented, the author has used es6-symbol.

The motivation behind using Symbol is to provide a stateless public API with a low memory footprint. The ES6 wiki describes one of the use cases for Symbol as lightweight information hiding, so a linked list seems like a good example. In LiLL, information about neighbours is stored on the actual items, so you can hop from item to item without creating an entirely new data structure.

LiLL is attached to an owner object using Lill.attach, then you can call Lill.getNext(owner, item) or getPrevious. There are also methods for getting the head and tail.

To build and iterate over a list, you could do this:

var Lill = require('lill');
var scores = {};
Lill.attach(scores);
Lill.add(scores, { name: 'AAA', score: 1000 });
Lill.add(scores, { name: 'ZZZ', score: 900 });

var item = Lill.getHead(scores);

while (item) {
  console.log('High score:', item.name, item.score);
  item = Lill.getNext(scores, item);
}

If you run this in Node’s REPL you’ll see entries with @@lill related data added to the owner object (scores), which describe the linked list. When Symbol is available without a shim then this will become symbols instead.

tcomb-validation, Bug Life

29 Aug 2014 | By Alex Young | Comments | Tags node validation data github graphs

tcomb-validation

tcomb-validation (GitHub: gcanti / tcomb-validation, License: MIT) by Giulio Canti is a general purpose validation library that can be used with (or without) React and Backbone.

It’s based on the tcomb library which is a runtime type checking library.

Using the plain JavaScript API, you can check types like this:

var t = require('tcomb-validation');
var validate = t.addons.validation.validate;

validate(1, t.Str).isValid();
validate('a', t.Str).isValid();

If you call firstError, you’ll get an Error object with a description of what failed the validation. You can combine validators using the struct method, and these can be passed to validate so you can validate forms. You can even pass a JSON schema to validate.

The Backbone integration works by calling validate like this:

var Model = Backbone.Model.extend({
  validate: function (attrs, options) {
    return validate(attrs, Attrs).errors;
  }
});

Bug Life

Bug Life

Bug Life was created for the GitHub Data Challenge, and displays a chart derived from issue data. It includes the labels and issue life cycle events, so you can see what the common labels are and how long it takes to close issues.

The screenshot I included was of Backbone, and generating it required authorisation with the GitHub API. Bug Life handles this quite well – once the API limit was hit I just had to click Authorize and that was pretty much it.

The author has included some explanations of the charts on the project’s demo page:

This is a popular repo on github - backbone. It has a rich history, well organized labels and release cycles. On version 0.9.0, when backbone reached a relatively stable state, many issues were closed. Before this release there were other important ones, for example 0.5.0.

After 0.9.0 backbone lived through 3 other important milestones: 0.9.9, 1.0.0 and 1.1.0. Each of these releases was focused on different aspects. Right before version 0.9.9 most open issues were of type change, while before version 1.1.0 most open issues were of type bug.

Google Get MEAN

28 Aug 2014 | By Alex Young | Comments | Tags node services google

Google MEAN

Melissa from Linnovate, the company behind MEAN.IO, wrote in to say Google have announced support for MEAN on Google Compute Engine.

Normally when I think of Google I think Java and Python. Other services including Heroku and Azure support a wide range of platforms, including Node, so it’s exciting to see Google offering MEAN.

The developer guide is here: MEAN development stack on Google Compute Engine, but it’s worth noting that the MEAN stack can be brought up with click-to-deploy. That means you can get MongoDB, Express, and Angular running in minutes, using a web-based wizard.

I’m not exactly sure how the pricing works with MongoDB, because SQL database pricing is different from Compute Engine. I created a click-to-deploy MEAN project and it seemed to show all the resources under Compute Engine, so I think that means all prices are based on CPU/disk usage.

I make a lot of Express apps, and Google’s developer tools (including the web console) seem compelling even next to Heroku and Azure, so I’d definitely like to try this for a real project soon!

Node Roundup: Tint, Redbird

27 Aug 2014 | By Alex Young | Comments | Tags node modules mac native http proxy

Tint

Tint2

Desktop apps built with node-webkit or similar technologies are on the rise. The idea is seemingly simple: package the Node runtime along with a small program that runs your Node web app as if it’s a native application.

Tint is an alternative. It uses a modified version of Node that bridges to native components, so you can actually write JavaScript that creates native Mac windows, buttons, web views, dialogs, and more.

It’s created by a company called True Interactions, and is MIT licensed. If you’re an Objective-C developer you might like to check out Main_mac.mm, because this is where the authors have successfully integrated Objective-C++ with Node’s event loop.

I built it from source and created a quick test application this afternoon to see what the API feels like:

require('Application');

var Window = require('Window');
var Button = require('Button');

var mainWindow = new Window();
var button = new Button();

mainWindow.title = 'DailyJS';

button.title = 'Hello';
button.addEventListener('mousedown', function() {
  button.title = '^_^';
});

button.addEventListener('mouseup', function() {
  button.title = 'Hello';
});

mainWindow.appendChild(button);

mainWindow.addLayoutConstraint({
  priority: 'required',
  relationship: '=',
  firstItem: button,
  firstAttribute: 'top',
  secondItem: mainWindow,
  secondAttribute: 'bottom',
  multiplier: 0.0,
  constant: 0.0
});

setInterval(function() {
  button.title = Math.random();
}, 1000);

I ran the script with ./build/Release/tint example.js and got a window with a button. I wrote this script by looking at the tests to see how the API works.

I think this is a cool project and I’d really like to make a real Mac application with it, but I’m not sure how to actually distribute an application bundle that people can easily install. I’ll keep playing with it and write a longer tutorial if I discover anything.

Redbird

Redbird (GitHub: OptimalBits / redbird, License: BSD, npm: redbird) by OptimalBits is a reverse proxy for dealing with dynamic virtual hosts, load balancing, proxying web sockets and SSL encryption.

var proxy = require('redbird')({port: 80});

// Route to any global ip
proxy.register('optimalbits.com', 'http://167.23.42.67:8000');

// Route to any local ip, for example from docker containers.
proxy.register('example.com', 'http://172.17.42.1:8001');

The documentation includes a full SSL example, and the authors are planning support for load balancing and IP filtering.

jquery.smoothstate.js, underscore-tpl

26 Aug 2014 | By alex young | Comments | Tags libraries ui jquery animation

jquery.smoothState.js

jquery.smoothState.js (GitHub: weblinc / jquery.smoothState.js, License: MIT) by Miguel Angel Perez promises to improve the early page loading experience by reducing the amount of sudden visual cuts.

By using unobtrusive JavaScript, jquery.smoothState.js loads content asynchronously and updates the URL with history.pushState. Animations are used as a visual cue to indicate when the main page content has been replaced.

The project’s documentation uses these techniques, but take a look at the demo for a more basic example to get started.

underscore-tpl

underscore-tpl (GitHub: creynders / underscore-tpl, License: MIT) by Camille Reynders allows you to expand placeholders stored within objects:

var config = {
  baz: '<%= qux.mofo %>',
  major: {
    badass: '<%= badass %>'
  },
  '<%= foo %>': 'bar'

It can use mustache-style tags instead of ERB, and accepts the same options as _.templateSettings.

I’ve found myself using this type of thing for generating seed data or fixtures in tests, but I imagine it might also be useful if you’re passing plain objects around with data-binding libraries as well.

PojoViz

25 Aug 2014 | By Alex Young | Comments | Tags libraries ui visualisation

Pojo Viz

Pojo Viz (GitHub: maurizzzio / PojoViz, License: MIT) by Mauricio Poppe is a JavaScript code visualisation tool. It shows plain objects and how they’re related, so you can quickly see that AngularJS has a fairly wide and flat hierarchy, where as Lo-Dash is very tall.

It works by analysing the global entry point to a library, then iterating over each property. If an object is encountered, then the properties of that object are recursed until a predefined maximum number of levels is reached.

You can use it to look at JavaScript’s built-in objects and types, although window is presented as a special case because it’s quite large.

It supports two renderers: SVG and WebGL. These use d3 and three.js, and it uses Polymer and Browserify as well.

Ment.io, Coffea, Marilyn

22 Aug 2014 | By Alex Young | Comments | Tags libraries ui WebSocket angularjs

Ment.io

Ment.io

Ment.io (GitHub: jeff-collins / ment.io, License: MIT) is a UI component for handling Twitter/GitHub style @ mentions. It has no dependency on jQuery, and it’s designed for use with AngularJS.

An ngModel is used for data, and the mentio-menu element is used to define the menu that appears during typing. You can use the mentio on a suitable input or content editable element to indicate where Mentio should appear.

Coffea

Coffea (GitHub: caffeinery / coffea, License: BSD, coffea) by Daniel Bugl is an event-based IRC client library. It supports SSL, and the API seems very friendly to Node developers:

var client = require('coffea')({
  host: 'irc.freenode.org'
});

client.on('motd', function(motd) {
  client.join(['#foo', '#bar', '#baz']);
});

client.on('message', function(event) {
  console.log('[' + event.channel.getName() + '] ' + event.user.getNick() + ': ' + event.message);
});

Marilyn

Marilyn (GitHub: alanjames1987 / marilyn, License: MIT) by Alan James Pub/Sub model API with a similar API to Mongoose. It’s event-based, so you can hook into events that are triggered before and after CRUD operations.

You can create models like this:

var MyModel = Marilyn.model('someModelName');

The before and after events can be defined in the initialisation callback that gets passed to the model method.

Marilyn.model('someModelName', function() {
  this.before('create', function(data, next) {
    // this is useful for validating data before a CRUD method runs
    console.log('I ran before');
    next();
  });

  this.after('create', function(data, next) {
    // this is useful for altering data before it's returned to the controller
    console.log('I ran after');
    next();
  });
});

LowDB

21 Aug 2014 | By Alex Young | Comments | Tags modules libraries node databases json

LowDB (GitHub: typicode / lowdb, License: MIT, npm: lowdb) by typicode is a JSON database that uses Lo-Dash. Rather than using a MongoDB-inspired API, it feels more like functional JavaScript.

Data is queried using familiar chained operators, ending in value when you want to obtain the result:

var topFiveSongs = low('posts')
  .where({ published: true })
  .sortBy('views')
  .first(5)
  .value();

LowDB accepts some configuration options, allowing you to control how it behaves. For example, if you want to use it like an in-memory database, then you can set autoSave to false:

var low = require('lowdb')
low.autoSave = false;

There’s also a short syntax API for the basic operations. To perform a where query, you can do this:

low('songs', {title: 'low!'})
// -> low('songs').where({title: 'low!'}).value()

low('songs', {published: false}, {published: true})
// -> low('songs').updateWhere({published: false}, {published: true}).value()

It doesn’t seem to work with localStorage, which I think would be cool, but it might work with Browserify.

Node Roundup: 0.10.31, One-Shot Budapest, Tenso

20 Aug 2014 | By Alex Young | Comments | Tags modules libraries npm node events

0.10.31

Node has been updated to 0.10.31, which includes a newer version of v8, openssl, npm, and bug fixes for some core modules. This includes a fix for fs where fs.readFileSync could leak file descriptors, and a fix for Readable.wrap’s handling of objectMode falsy values.

One-Shot Budapest

The NodeConf One-Shot: Budapest conference will be held on November 21th, 2014. Tickets are $100, and talks include:

  • Matteo Collina: Hardware Hacking on Stage
  • Mathias Buus: BitTorrent, p2p with Node.js
  • Julian Gruber: Node.js vs Go
  • Nuno Job: Production Ready Node

Tenso

Tenso (GitHub: avoidwork/tenso, License: BSD-3, npm: tenso) by Jason Mulligan is a REST API facade. It supports caching, DTrace, and decorates response/request objects in a similar way to Express/restify.

var uuid = require( 'keigai' ).util.uuid;

module.exports.get = {
  '/': [],

  '/reports/tps': function(req, res) {
    res.error(new Error('TPS Cover Sheet not attached'), 785);
  },

  '/uuid': function(req, res) {
    res.respond(uuid(), 200, {'cache-control': 'no-cache'});
  }
};

DeLorean, Cash: Call, Collect, Assign

19 Aug 2014 | By Alex Young | Comments | Tags libraries ui flux

DeLorean.js

DeLorean.js (GitHub: f / delorean, License: MIT, Bower: delorean, npm: delorean.js) by Fatih Kadir Akın is a Flux implementation. It can be used with React.js and Flight.js, and the author mentioned that he’s working on Backbone.js integration as well.

I’ve previously written about Fluxxor, which is another library based on Flux. If you’ve used MVC libraries before, then you can think of DeLorean.js and Fluxxor like alternatives for the models and controllers. Flux provides tools for creating stores, dispatchers, and action creators.

Stores are a bit like models, but you don’t create instances of them. Instead they manage state for a domain within the application. This actually has positive implications for testing. This quote is from the React overview:

Stores accept updates and reconcile them as appropriate, rather than depending on something external to update its data in a consistent way. Nothing outside the store has any insight into how it manages the data for its domain, helping to keep a clear separation of concerns. This also makes stores more testable than models, especially since stores have no direct setter methods like setAsRead(), but instead have only an input point for the payload, which is delivered through the dispatcher and originates with actions.

Dispatchers manage data flows, responding to actions as they are created during the lifetime of a program. Action creators are similar to controllers in MVC – in DeLorean’s documentation they do things like get JSON from a server, then pass the data to a dispatcher.

Action creators are then used by the view layer, so if you’re using React you could invoke action creators from views and bind them to template fragments.

This might all sound highly abstract, but you might find it useful if you’re finding it hard to manage large client-side projects. The model layer in MVC libraries often feels ORM-inspired, which in my experience doesn’t always work well when combined with business logic.

Cash Updates

Rob Robbins sent in a note to say Cash has been updated to include new methods for allowing the invocation of native functionality:

Call, Collect and Assign

In order to keep code creep at a minimum, We are introducing these three methods that allow the invocation of native functionality on the elements in the q. What do I mean? Let’s take the Attribute methods for an example. We could write separate methods for the getting, setting, and removal of attributes:

cash.setAttribute = function(foo, bar) {
  // set attribute 'foo' to 'bar' on each element in the q 
};

cash.removeAttribute = function(foo) {
  // remove attribute 'foo' from each element in the q 
};

cash.getAttribute = function(foo) {
  // collect and return attribute 'foo' from each element in the q 
};

Instead we can have a single method capable invoking any of these (or any native method for that matter):

$(foo).call('setAttribute', 'data-foo', 'bar'); // returns cash
$(foo).call('removeAttribute', 'data-foo');
$(foo).collect('getAttribute', 'data-foo'); // retruns an array

The reason I wrote about Cash previously was because I know a lot of people are looking for alternatives to jQuery for smaller DOM/event-wrapper libraries, and this new API should help people use existing standards rather than reinventing things browsers are good at.

PerfBar, ngAtp

18 Aug 2014 | By Alex Young | Comments | Tags libraries ui angularjs performance benchmarks

PerfBar

PerfBar

PerfBar (GitHub: lafikl / perfBar, License: MIT) by Khalid Lafi is a script that adds various benchmarks to a page. To use it, add perfBar.js and then configure some metrics:

perfBar.init({
  budget: {
    'loadTime': {
      max: 200
    },
    'redirectCount': {
      max: 1
    },
    'globalJS': {
      min: 2,
      max: 5
    }
  }
});

You can use perfBar.enable and perfBar.disable to toggle metrics. The documentation has PerfBar included on the page so you can see what it looks like, and each of the available metrics is documented.

Some of the available metrics are the total number of DOM elements, the time for the DOM content to load, request duration, and backend/frontend processing time.

ngAtp

ngAtp (GitHub: yiransheng / ngAtp, License: MIT, Bower: ng-atp) by Yiran Sheng is an autocompletion library for AngularJS. The basic usage is to specify the ng-atp and ng-atp-config directives. The config option uses a Bloodhound config object, which comes from Twitter’s typeahead.js suggestion engine.

In ngAtp, Bloodhound is included as an Angular service, with Angular’s $http library instead of jQuery.ajax. It reuses Bloodhound, so you get features like prefetching, intelligent caching, fast lookups, and backfilling, but with an Angular-friendly API.

Js13kGames, Angular Plasmid

15 Aug 2014 | By Alex Young | Comments | Tags games competitions graphics biology angularjs testing

Js13kGames

Andrzej Mazur wrote in to say that the Js13kGames competition has started. All entries must be in by the 13th of September. It’s a competition to build HTML5 games in 13 kilobytes, and that includes all assets. If you want sounds and complex graphics then it might be advantageous to procedurally generate certain things.

All your code and game assets should be smaller than or equal to 13 kilobytes (that’s exactly 13,312 bytes, because of 13 x 1024) when zipped. Your package should contain index.html file and when unzipped should work in the browser.

The competition has a theme, so entries should somehow encapsulate the elements:

The main theme of the competition in 2014 is The Elements: Earth, Water, Air and Fire. It is optional, so you can use it, use part of it (one Element), or drop it. Remember that there will be bonus points for implementing the theme in your game.

Andrzej wrote a tutorial for tuts+ about minifying games, and he created the game Triskaidekaphobia to promote the competition.

Angular Plasmid

Angular Plasmid

Angular Plasmid (GitHub: vixis / angularplasmid, License: MIT) by Rehan Chawdry is an AngularJS library for biological plasmid visualisation:

Rather than coding client-side JavaScript or other server-side programming languages, AngularPlasmid provides easy-to-use HTML markup, making plasmid generation as easy as creating a web page. In fact, you don’t really neeed to know anything about AngularJS or JavaScript to use the components, as one of the download options bundles everything together for you.

The basic tutorial explains how to create a visualisation using markup rather than having to write JavaScript, so it should appeal to biologists who want to create rich HTML documents that aren’t programmers. In fact, Angular seems like a good choice for this type of visualisation in that you can use it declaratively.

Amygdala: A JavaScript REST Client

14 Aug 2014 | By Alex Young | Comments | Tags rest libraries browser

Over the last few years I’ve worked almost exclusively by designing server-side APIs totally separately to the UI. Client-side code is just another client, structured with something like Backbone or Angular. This works well when you develop applications that have multiple front-ends (public site, admin area), or you’ve got desktop and mobile clients.

Marco Louro sent in Amygdala (GitHub: lincolnloop / amygdala, License: BSD, npm: amygdala), a JavaScript REST library designed specifically for this type of work. It’s inspired by Hoodie, but optimised for custom API backends instead of a specific API or database.

Amygdala was born out of the desire to reduce the complexity involved with managing multiple JavaScript modules (controllers or models/collections) that do essentially the same thing, fetch and sync data.

It works by using a constructor function that accepts configuration and resource paths. Data is cached to localStorage, and updates to data after subsequent modifications results in events that you can subscribe to:

store.on('discussions:change', function() {
  // re-render our view
}.bind(this));

When you set up the RESTful API, you can specify things like HTTP headers and foreign key relationships:

var store = new Amygdala({
  'config': {
    'apiUrl': 'http://localhost:8000',
    'idAttribute': 'url',
    'headers': {
      'X-CSRFToken': getCookie('csrftoken')
    },
    'localStorage': true
  },
  'schema': {
    'users': {
      'url': '/api/v2/user/'
    },
    'teams': {
      'url': '/api/v2/team/',
      'orderBy': 'name',
      'oneToMany': {
        'members': 'members'
      }
    },
    'members': {
      'foreignKey': {
        'user': 'users'
      }
    }
  }
});

When I use a library that focuses on data binding, like Knockout, server communication always feels hard to get right. Amygdala looks like a great library to pair with Knockout – it’ll help make server calls cleaner and also add locally cached data without much extra effort.

Node Roundup: npmE, Snapshot.js, dm.js

13 Aug 2014 | By Alex Young | Comments | Tags node modules libraries npm dependency-injection

npmE

There’s an open beta for npmE, the npm Enterprise programme. This allows you to sign in to a private, hosted repository, which can be used to distribute private modules. They’re prefixed with your company name, like this:

npm install @myco/somepackage

Then you can load them with the prefix as follows:

require('@myco/somepackage');

There’s a new post on the npm blog about the roadmap for npmE:

We plan on building a web-UI for controlling various aspects of an npmE installation: adding and removing packages from the whitelist, configuring authentication/authorization strategies, managing organizations and teams.

Snapshot.js

Snapshot.js (GitHub: Wildhoney/Snapshot.js, License: MIT, Demo) by Adam Timberlake is a WebSocket-based Node application for sorting, paginating, and filtering data served using WebSockets.

It uses Express and the crossfilter module, which is a multidimensional filtering library:

Crossfilter is a JavaScript library for exploring large multivariate datasets in the browser. Crossfilter supports extremely fast interaction with coordinated views, even with datasets containing a million or more records; we built it to power analytics for Square Register, allowing merchants to slice and dice their payment history fluidly.

dm.js

dm.js (GitHub: gobwas / dm.js, License: MIT, npm: dm) by Sergey Kamardin is a module for dependency injection. It’s service based, so you’d have to build applications using that pattern to take advantage of it.

The dm module itself implements the “service locator” pattern. That means it knows how to find a given service and configure it. It supports asynchronous adapters, so you could use it with jQuery.Deferred, Q.js, and promises with Harmony. It can load modules with either AMD or CommonJS, so it’ll work with Node modules.

This might sound like a huge amount of effort if you’re not used to dependency injection, but if you come from a Java/C#/C++ background then you might find it easier to design Node applications this way.

Build Configuration with Angus

12 Aug 2014 | By Alex Young | Comments | Tags build grunt

Angus

Build tools are great, but they’re usually optimised for working on single projects. If you’re a freelancer or work for an agency, then you probably work on multiple projects for several clients each day. Angus (GitHub: nickjanssen / angus, License: MIT) by Nick Janssen aims to help improve exactly that type of workflow by sharing a build configuration across all of your applications.

Angus solves these problems by turning the build process into something generic and reusable. It allows you to specify libraries on a per-app basis, while still sharing the same build steps.

Inside Angus, every app is simply a directory inside the apps/a folder with its own repository. The apps/ folder gets ignored by the Angus repository. Each app you make with Angus shares the same global Gruntfile, but can define all the libraries they need on a per-app level.

Each application can still have its own dependencies. Bower is used for client-side dependencies, but rather than using bower.json files Angus invokes Bower with the necessary package names and version strings.

Nick posted an article to David Walsh’s blog about Angus: Building Web Apps Faster Using Angus. It details the installation and configuration process and also shows how to use Angus with Git.

Backbone Directives

11 Aug 2014 | By Alex Young | Comments | Tags backbone angularjs libraries

Tal Bereznitskey writes:

This is an open source project to enrich Backbone.js with AngularJS style directives.

I used to hear people talk about the new hotness and I didn’t really want to let go of Backbone. I took quick looks from time to time and found some stuff I didn’t like in AngularJS.

The DOM was filled with things like “ng-click” which reminded me of the spaghetti age of HTML and JavaScript.

When I first started using Angular I also found custom attributes (directives) concerning. However, after using them I realised that they can really help make code more declarative and concise. Tal came to the same conclusion, and created Backbone Directives (GitHub: berzniz / backbone.directives, License: MIT) to bring the same pattern to Backbone projects.

It includes things like bb-bind which implements data-binding with expression support, and bb-class for changing an element’s class.

Expressions use the same code as Angular’s expression parser, which attempts to safely execute JavaScript by using a sandbox that prevents access to certain properties (like .constructor).

// Sandboxing Angular Expressions
// ------------------------------
// Angular expressions are generally considered safe because these expressions only have direct
// access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by
// obtaining a reference to native JS functions such as the Function constructor.

Not all data binding libraries support expressions as well as this, so Tal has opted to fork Angular’s approach so you can get the same functionality in your Backbone applications.

Tal wrote a post about the project, with his thoughts on Angular, Backbone, and how to use Backbone Directives.

Face Tracking, tcomb

08 Aug 2014 | By Alex Young | Comments | Tags graphics webcam

JavaScript Face Tracking

Konrad Dzwinel sent in a JavaScript Face Tracking Demo that demonstrates how to use getUserMedia with tracking.js to track your face and add an image based on the position. It also uses gif.js to generate GIFs, and Imgur’s API to upload the images.

Konrad made a video about the project with more details about each of the libraries and how you can use them.

tcomb

tcomb (GitHub: gcanti / tcomb, License: MIT, npm: tcomb) by Giulio Canti is a library for making types and combinators. You can use it for validating input or perhaps even lightweight models.

It supports JavaScript primitive type checking, structs, unions, tuples, and subtypes. This is an example of a struct:

var Product = struct({
  name: Str,                  // a REQUIRED string
  description: maybe(Str),    // an OPTIONAL string (can be `null`)
  homepage: Url,              // a SUBTYPE of string representing an URL
  shippings: list(Shipping),  // a LIST of shipping methods
  category: Category,         // a string in [Audio, Video] (ENUM)
  price: union(Num, Price),   // price expressed in dollars OR in another currency (UNION)
  dim: tuple([Num, Num])      // width x height (TUPLE)
});

The project is tested with Mocha, and the readme and homepage have lots of examples.