Holiday Reading for JavaScript Programmers

22 Dec 2014 | By Alex Young | Comments | Tags books tutorials

Hemingway and JavaScript

If you’re lucky enough to be enjoying a festive holiday right now, then you’re probably starting to get bored of Christmas movies and long dark teatimes of the soul. Rather than knuckling down with the family to watch Elf for the umpteenth time, why not load up your favourite reading device with some programming books and articles?

Angus Croll sent in a copy of his book If Hemingway Wrote JavaScript (No Starch Press, $15.95), which makes comparisons between literary figures and programming styles. This book started as a blog post about Hemingway, and there are amusing posts on his blog, like Animals writing JavaScript. I thought it would be hard to stretch the original idea out into an entire book, but Angus uses the concept to explore the broader question of how we write and think about JavaScript:

JavaScript has plenty in common with natural language. It is at its most expressive when combining simple idioms in original ways; its syntax, which is limited yet flexible, promotes innovation without compromising readability. And, like natural language, it’s ready to write. Some of JavaScript’s more baroque cousins must be edited with an IDE (integrated development environment—a sort of Rube Goldberg machine for coding). JavaScript needs nothing more than a text file and an open mind.

The question of style in programming is usually approached with defensive trepidation, but the literary conceit allows Angus to present different stylistic ideas without judging them. For example, Virginia Woolf’s poetic stream of consciousness is recreated with a mix of long lines and flexible use of semicolons:

If the semicolon is the period of JavaScript, then the comma operator is its semicolon. Programmer Woolf loves the comma operator, and in her happy numbers solution, she uses it to excess. The result is a dreamy, melancholic form of JavaScript (is there any other?) made dreamier still by the heavy, almost dangerous level of n alliteration and some gorgeously expressive pairings. In To the Lighthouse, Woolf writes of night’s shadows: “They lengthen; they darken”; in her happy numbers solution we get the wistfully poetic numerals.shift(), numerals.length.

I commute across London everyday and read to pass the time. Over the years I’ve moved from pulp sci-fi to 20th century modernists and the classics, so this book is ideal for me. I’m not sure how many literary programmers there are, however, so this is definitely a novelty that I will cherish.

Other readers have also recently sent in some interesting resources that you might like to read over the holiday. Thai Pangsakulyanont’s JavaScript for Automation Cookbook contains examples for Apple’s new scripting system that allows you to control Yosemite applications with JavaScript. It includes iTunes, Safari, system events, and how to use CommonJS modules with Browserify, so you can actually make maintainable automation scripts.

Eugene Abrosimov sent in a big list of Backbone.js tutorials, articles, videos, and examples. There should be a few things on there to load up Instapaper/Pocket if you use Backbone.

And, just over a week ago I received the first print of my book, Node.js in Practice (Manning, $39.99). I wrote it with Marc Harter, and we’ve designed the book for intermediate to advanced Node developers. Our publisher, Manning, also publishes Node.js in Action (Manning, $35.99) which is well suited to new Node programmers.

Rantjs, Avatar, esformatter

19 Dec 2014 | By Alex Young | Comments | Tags text graphics atom plugins

Rantjs

Rantjs (GitHub: svenanders/Rantjs, License: ISC, npm: rantjs) by Sven Anders Robbestad is a library for procedurally generating text. It takes a formatted constructor and then generates suitable sentences:

var rantjs = require('rantjs');
var rant = new rantjs.SimpleRant;
var sentence = rant.rantConstructor('<firstname male> likes to <verb-transitive> <noun.plural> with <pron poss male> pet <noun-animal> on <timenoun dayofweek plural>.');

console.log(sentence); // 'Sean likes to chop parrots with his pet cat on Saturdays.'

There are a lot of supported tags, with subgroups, so you can generate a activity video or adv emotion. You can also add your own tags.

The author suggests that this might be useful for generating random text in games, but I think it might also work well for generating random admin area sample text in a blog or CMS, and for creating text to use in testing.

Avatar

If you’re looking for a way to generate default avatars, then take a look at Avatar (GitHub: MatthewCallis/avatar, License: MIT, npm: avatar-initials) by Matthew Callis. It can show the user’s initials in a styled or unstyled avatar, or optionally fall back to a Gravatar instead.

To use it, just instantiate Avatar with the container element:

var avatar = new Avatar(document.getElementById('avatar'), {
  useGravatar: false,
  initials: 'MC'
});

/* or */

$('#avatar').avatar({
  useGravatar: false,
  initials: 'MC'
});

esformatter

Sindre Sorhus sent in atom-esformatter (GitHub: indresorhus/atom-esformatter, License: MIT), an Atom editor package for formatting JavaScript with esformatter. Esformatter itself supports lots of options for formatting JavaScript, like the indentation characters, line breaks, and whitespace handling.

Sindre’s Atom package lets you run esformatter from the Command Palette by typing esformatter, and you can run it on a selection or the whole file.

Esformatter supports plugins, so you can change its behaviour by loading other Node modules. There’s a list of plugins and also a plugin wish list. Sindre notes that it can be used with Gulp and Grunt, which might be a good way of processing open source JavaScript according to your project’s style guide before you release it.

React Roundup: rc-calendar, D3 React Reusable Charts, tcomb-form

18 Dec 2014 | By Alex Young | Comments | Tags libraries react components

rc-calendar

rc-calendar (GitHub: react-component/calendar, License: MIT) by yiminghe is a port of kissyteam/date-picker that allows you to render calendars with React.render(<Calendar />, container). It has props for locale, showing today, and the select/blur events, and it includes some examples and tests.

The supported locales are en-us and zh-cn, so you can actually display a Chinese calendar UI. It also supports aria and keyboard accessibility.

D3 React Reusable Charts

d3rrc

D3 React Reusable Charts (GitHub: jdarling/d3rrc, License: MIT, npm: d3rrc) by Jeremy Darling is a graph library that supports bar charts, pie charts, scatter charts, and time series. It allows you to use a LineChart element. This code is taken from the multi-line chart example:

React.render(
  <LineChart
    chart-height="320"
    chart-seriesNames={seriesNames}
    chart-seriesValues={seriesValues}
    chart-pointNames={pointNames}
    chart-pointValues={pointValues}
    chart-lineInterpolation="cardinal"
    data={data}
  />,
  document.getElementById('output')
);

React makes graphs quite clean by allowing you to mix the markup and JavaScript data. For more examples, take a look at the full d3rrc example list.

tcomb-form

tcomb-form (GitHub: gcanti/tcomb-form, License: MIT) by Giulio Canti is a UI library for making forms. As we all know, making forms is web development drudgery, so anything to take the pain away is welcome. Giulio’s library is “domain driven”, which means it’s able to generate a form based on the domain model.

There’s a personal form example that shows the kind of form I’ve spent all too much time creating in the past. The source uses a kind of strongly typed model definition approach:

var t = require('tcomb-form');

var Gender = t.enums({
  M: 'Male',
  F: 'Female'
});

var Country = t.enums({
  US: 'United States',
  IT: 'Italy'
});

var Person = t.struct({
  fullName: t.Str,
  nickname: t.maybe(t.Str),
  gender: Gender,
  country: Country,
  tags: t.list(t.Str)
});

var Form = t.form.create(Person, {
  auto: 'labels',
  fields: {
    gender: {
      factory: t.form.radio
    }
  }
});

You don’t have to use this to define the actual models in your application. With this library, it might be better to use a lightweight model/view model approach, so you’d treat the tcomb models as view models that define the behaviour specific to forms.

Node Roundup: watch-network, MailDev, node-notifier

watch-network

If you use something like Docker or Vagrant and want to listen for file notifications over the network, then watch-network (GitHub: efacilitation/watch-network, License: MIT, npm: watch-network) by Johannes Becker might come in handy. It can be used with Gulp, so you could run Gulp tasks when a specific network notification comes in.

Here’s a basic example:

var watch = WatchNetWork({
  configs: [{
    patterns: 'lib/*.coffee',
    tasks: 'something:important',
    onLoad: true
  }]
});

watch.task('something:important', function(changedFiles) {
  // ..
});

watch.initialize();

Here’s the use-case that Johannes described:

Scenario: You use Vagrant/VirtualBox in your workflow to have services and configurations in an encapsulated environment. For developing purposes you now sync a local directory into the VM using vboxfs, nfs, rsync or similar. In your VM you want to use watcher facilities for developing-concerns, but for some reason triggering inotify over the network seems to be troublesome or unreliable.

MailDev

MailDev

If you’ve ever felt like handling emails in web applications is messy, and you don’t feel like your emails are as good as they could be, then you’re not alone! I always feel like emails are annoying to develop, so I thought MailDev (GitHub: djfarrelly/maildev, License: MIT, npm: maildev) looked interesting. This module helps you test your project’s generated emails during development with a responsive web interface. It has a Node API, and there’s even a REST API so you could integrate it with other services.

Emails are displayed with WebSockets, so you don’t have to keep refreshing, and it’ll show HTML, text, and attachments.

I currently send all the generated emails to a temporary directory, then open them up when I need to. MailDev seems like a much better solution.

node-notifier

Mikael Brevik sent in node-notifier (GitHub: mikaelbr/node-notifier, License: MIT, npm: node-notifier), in response to the recent mention of trayballoon. Node-notifier tries to smooth out the differences between each platform, so you can use notification features that are present on all platforms more easily. It also supports actions on notifications.

Mikael notes that it works with node-webkit, which is cool if you’re making Node desktop apps, and it supports the following notification systems:

  • Mac: Notification Center, Growl
  • Windows: Toasters, trayballoon
  • Linux: notify-osd

Here’s an example:

var notifier = require('node-notifier');
notifier.notify({
  'title': 'My notification',
  'message': 'Hello, there!'
});

JavaScript Developer Survey 2014: Results

16 Dec 2014 | By Alex Young | Comments | Tags community surveys

The JavaScript Developer Survey has now closed. As always the results are available to the community for further analysis:

Browser-based developers are still the majority.

97% of readers write client-side code, while 56% said they write server-side code. Last year server-side development was at 28%. I’d like to think that the interest and adoption of technologies like Node will contribute to the direction of ECMAScript, because some proposals seem to go against the strides that have already been made in the Node community (the module system, for example).

The DailyJS readership is very experienced (27% said 5-10 years), so perhaps I should do more to cover advanced topics?

78% of readers said they don’t use a language that compiles to JavaScript – both this year and last year. I’ve written more about technologies like TypeScript this year, partly because I respect that project in particular, but Dart is also compelling. However, Dart was one of the least popular compile-to languages (1%). TypeScript is more popular (5%), but CoffeeScript is still the most popular (16%).

It turns out most people like semi-colons. I think they’re going to stick around in the JavaScript community because they’re used in so many other languages, but it’s always possible that styles will change over time. According to the survey results, the stylistic choices are actually similar to some of the more popular JavaScript style guides.

ES6 features are getting popular: 24% said they use ES6. I suspect that more people actually do use them, because 'use strict' is something I’ve seen in lots of JavaScript best practice articles. Also, Node frameworks like Koa use cool features like generators quite well, so I think this figure will grow over the next year.

Testing: 29% said they write tests. I was interested to see that PhantomJS is a very popular test environment (38%). I’ve mentioned many times on DailyJS that I struggle a little bit when it comes to this type of testing, because the tests seem to become brittle and break over time. However, the number of people that use PhantomJS is close to Node, so presumably most people have found a way to make it work well enough.

Jasmine and Mocha are still the most popular test frameworks, and Karma is gaining on them now as well.

61% use JSHint for static analysis. That’s 2608 people, which surprised me because I don’t often use a linter. I think it might be down to people verifying open source client-side JavaScript, but it would be interesting to find out exactly why people are motivated to lint JavaScript.

Gulp (35%) is already almost as popular as Grunt (47%). It’s amazing how quickly Gulp has been adopted, although I’ve found I can understand Gulp more readily than Grunt scripts.

When it comes to client-side dependencies, CommonJS with Browserify is at 20%, with plain old files at 30%. I think that’s interesting because Browserify is my preferred solution, but I often use plain old files because I’m working on a legacy project where Browserify is a luxury we don’t have time for.

AngularJS is strangely popular (49%). I’ve noticed that many in the JavaScript community regard React (16%) as the latest hot framework and see it as an alternative to Angular, but they do different things so I prefer to use the appropriate tool for each project. Meteor is a lot less popular than the hype had me believe (6%), but it’s possible that DailyJS readers don’t like Meteor. It’s worth noting that Backbone.js is popular, with 31%.

SublimeText won the editor wars, although a fair few readers use IDEs like IntelliJ and Visual Studio.

The most popular minimum IE is IE 9. I find that’s interesting because I still get asked to support 8 for corporate networks that can’t seem to untangle themselves from web-based legacy software (do any readers use ADP for example?)

Here are the top “other” programming languages:

  1. PHP
  2. Java
  3. C#/.NET

I still find it strange that PHP is so popular, although it’s 6 on the TIOBE index, and this is primarily a web development blog after all.

Thanks to everyone who took part in the survey! If you’d like me to run another rather than waiting for a whole year, then get in touch with your ideas.

Survey Closed, Predicates, Shackles

15 Dec 2014 | By Alex Young | Comments | Tags surveys modules libraries assert

Survey Closed

The JavaScript Developer Survey 2014 has now closed. I received some updates for the survey to the GitHub repository, so you should see those the next time I run it. Thanks for the contributions!

I’ll work on writing up the results and post again when they’re ready.

Predicates

Predicates (GitHub: wookieb/predicates, License: MIT, npm: predicates) by Łukasz Kużyński is a set of tools for type checking and assertions. For example:

var is = require('predicates');

is.string(1); // false
is.string('test'); // true
is.undefinedOr(is.string, undefined); // true

Assertions look like this:

var assertName = createAssert(is.string, 'Name must be a string');

var Person = function(name, surname, age) {
  assertName(name);
  assertSurname(surname);
  assertAge(age);
}

new Person('Tom', 'Welling', 33); // OK!

The Predicates API guide has a list of each available method, and there’s also an interesting API design document that provides some background to the project.

Shackles

Shackles (GitHub: metaraine/shackles, License: ISC, npm: shackles) by Raine Lourie is a module for adding chaining to another library. Imagine if Underscore didn’t support chaining. You could use Shackles to create a fluent API, like this:

var chain = shackles(_);

var result = chain([1,2,3])
  .map(function (x) { return x*x })
  .filter(function (x) { return x > 2 })
  .value(); // [4,9]

You can insert values at any point in the chain with tap, and there’s also a log method that prints values with console. Logging can be overridden as well.

AsyncTask, DefineJS ES6 Features

12 Dec 2014 | By Alex Young | Comments | Tags es6 generators webworkers

AsyncTask

Web workers are great, but who wants to go to the trouble of creating extra files just to run some code in parallel? AsyncTask (GitHub: gorillatron/async-task, License: MIT, npm: async-task) by Jørn Andre Tangen is a more generic web worker constructor that lets you define background tasks purely with JavaScript:

var task = new AsyncTask({
  doInBackground: function(a, b) {
    return a + b
  }
});

task.execute(1, 2)
  .then(function(result) {
    result === 3
  })
  .catch(handleException);

It has a fluent API, and has Karma/Mocha unit tests as well.

DefineJS: ES6 Generator Syntax

Recently I wrote about Mehran Hatami’s define.js project, which is a lightweight AMD implementation. It has just been updated to support ES6 generators for loading modules, which means you can do this:

var module = yield require('module');

It’s still asynchronous, but it looks synchronous. I think this is a really cool use of generators, and apparently several people asked Mehran to implement this so it seems like there’s demand for it.

New npm Site, Amelie Music Visualiser

11 Dec 2014 | By Alex Young | Comments | Tags npm audio

New npm Site

npm

npm has a new website! There’s an announcement blog post that explains what has changed, and what’s next, including this information about private modules:

Our next immediate goal is to support private npm modules on the website. This will allow individuals and teams to publish, install, and view private code using all the familiar npm mechanisms.

The website is now responsive, so it’ll look better on mobile devices. I found it looked nicer when I tiled my browser windows, which I often like to do when juggling material for DailyJS posts.

Amelie Music Visualiser

Amelie

Adam Timberlake sent in a music visualisation experiment made with React, D3, and SVG: amelie.herokuapp.com (GitHub: Wildhoney/Amelie, Bower: amelie). It uses AnalyserNode to get frequency data from the audio file:

The AnalyserNode interface represents a node able to provide real-time frequency and time-domain analysis information. It is an AudioNode that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations.

Because the AnalyserNode API does the more complicated FFT stuff, the source is actually fairly easy to understand. Take a look at Amelie.jsx to see how the colours are generated and then plotted using D3.js.

JavaScript for Kids, Eloquent JavaScript

10 Dec 2014 | By Alex Young | Comments | Tags books

JavaScript for Kids by Nick Morgan introduces programming by using JavaScript, HTML, and lots of games. It’s tailored for younger readers, but it’s more for teenagers than under 10s. You might be able to use it as a guide to teach someone under 10 though. Here’s a quote from the section on syntax:

Our program includes lots of symbols, including parentheses (), semicolons ;, curly brackets {}, plus signs +, and a few words that might seem mysterious at first (like var and console.log). These are all part of JavaScript’s syntax—that is, JavaScript’s rules for how to combine symbols and words to create working programs.

When you’re learning a new programming language, one of the trickiest parts is getting used to the rules for how to write different kinds of instructions to the computer. When you’re first starting out, it’s easy to forget when to include parentheses, or to mix up the order in which you need to include certain values. But as you practice, you’ll start to get the hang of it.

I remember when I was a kid, learning programming for the first time, and I was worried about learning the “best” programming language. I like the fact Nick suggests that you’re likely to learn other programming languages and points out the similarities.

The examples use HTML and JavaScript, so all you really need is a browser and editor. The earliest examples use the console debugger, so I can imagine kids turning up at school, opening the developer tools in a browser and impressing their friends with their newfound hacker skills.

The publisher (no starch press) has a discount for this book (today only): just enter LILCODER during checkout to get 40% off. The standard price for the e-book is $27.95.

No starch press also sent me the second edition of Eloquent JavaScript by Marijn Haverbeke. This book also introduces programming, so beginners may find it useful:

Besides explaining JavaScript, I also will introduce the basic principles of programming. Programming, it turns out, is hard. The fundamental rules are typically simple and clear. But programs built on top of these rules tend to become complex enough to introduce their own rules and complexity. You’re building your own maze, in a way, and you might just get lost in it.

However, at over 400 pages this edition includes a lot of content, including a chapter on performance, and a full-stack worked example in the Skill-Sharing Website chapter. The book covers client-side JavaScript, including some fun Canvas drawing examples, and Node.

Both of these books complement each other, and JavaScript for Kids may work well as the source material for something like Code Club.

ES6 Metaprogramming, Barn

09 Dec 2014 | By Alex Young | Comments | Tags es6 proxies redis browser localStorage

ES6 Metaprogramming

The last time I seriously looked at JavaScript metaprogramming I tried all kinds of dubious things like exploiting the with statement. With ECMAScript 6 proxies, the situation might be about to change. In Meta programming with ECMAScript 6 proxies, Dr. Axel Rauschmayer writes about the concept of metaprogramming, the different approaches (introspection, self-modification, intercession), and provides JavaScript examples.

This article includes an overview of proxies and what they’re useful for, and shows how they can be used for intercepting method calls. He also mentions how proxies impact performance:

Data binding is a complex topic. Given its popularity and concerns over proxies not being performant enough, a dedicated mechanism has been created for data binding: Object.observe(). It will probably be part of ECMAScript 7 and is already supported by Chrome.

This is an in-depth article that is worth taking some time over, but will influence many people who are creating the next generation of ECMAScript 6-based APIs.

Barn

Barn (GitHub: arokor/barn, License: MIT, npm: barn) by Aron Kornhall is an API for localStorage that is based on Redis. The idea is to make operations atomic, so they survive things like a tab being closed or unexpected exceptions.

If you’re used to Redis, then you might like this:

var barn = new Barn(localStorage);

barn.set('key', 'val');
console.log(barn.get('key')); // val

barn.lpush('list', 'val1');
barn.lpush('list', 'val2');
console.log(barn.rpop('list')); // val1
console.log(barn.rpop('list')); // val2

Internally a mutating flag is used to provide a locking mechanism around the localStorage access. I think this should prevent issues that you might get when performing multiple writes, because the Web Storage specification says writes don’t wait until the data has been written to disk.

Barn itself is based on NSStorage, which is also written by Aron. NSStorage is a smaller module that provides namespacing for the Web Storage API.

Mask.js, Sloc

08 Dec 2014 | By Alex Young | Comments | Tags build-tools browser jquery

Mask.js

Mask.js (GitHub: bguzmanrio/maskjs, License: GPL) by Borja Guzmán is a library for validating input fields against dates, numbers, and text. It allows people to type in dates using numbers so they don’t have to type in the necessary punctuation.

It prevents invalid input from being typed and allows you to skip between numbers, so it’s less rigid than some implementations.

The API uses methods on Mask:

Mask.newMask({
  $el: $('input.name'),
  mask: 'HH:mm',
  errorFunction: function() {},
  defaultValue: '12:00'
});

Sloc

If you want to generate metrics for a project like source code length, how do you do things like ignore comments and empty lines? Sloc (GitHub: flosse/sloc, License: MIT, npm: sloc, Bower: sloc-bower) by flosse handles these edge cases and more. It also supports lots of languages, including JavaScript, CoffeeScript, Lua, and Swift.

It comes with a command-line script that you can run with sloc file.js, and it’ll automatically recurse directories. There are options for ignoring files (--exclude pattern) and selecting an output format (--format [json|csv|cli-table]).

Sloc has a Node module, so you can require('sloc') and run sloc(source, language) to get an object with various statistics. The project itself is well-tested, and has some cool usages like atom-sloc.

Node Advisory Updates and Node Forks

05 Dec 2014 | By Alex Young | Comments | Tags community node

As someone who works professionally with Node and writes about it regularly, I’ve naturally been following the discussions about Node forks and the Node advisory board. I’ve been collecting articles in Instapaper and highlighting things like crazy to figure out what’s going on.

On Wednesday TJ Fontaine posted an advisory board update on the official Node blog. The board has had three meetings so far which you can follow on GitHub: nodejs-advisory-board/meetings.

The most recent minutes mention the ongoing discussions about the Node trademark:

The group will utilize Mongo, Eclipse, and Docker as examples projects to draw from. Agreed that there is no certification products and since there is no process to do that, there will be no certification for training or product compatibility. Project teams should be publishing the acceptance testing and organizations that want to test against the test suite and should be posting the results to the node.js repo

The advisory board have decided that the Node project should be run based on a consensus, rather than a dictatorship:

One thing that we all agree on, is that we’re not going to be using the Benevolent Dictator model. In fact, recently the project hasn’t been operating that way. We can be more clear about that in our documentation. We all agree we want a healthy and vibrant team, a team focused on making progress for Node.js, not for progress’s sake, but for the betterment of the software project and the community we serve.

The goal of the team, especially that of the project lead, is to drive consensus and ensure accountability.

This is followed by a list that indicates how API changes will be handled in the future. Also, there is news about Node 0.12:

Finally, we are very close to releasing v0.12, there’s only one major patch we’re waiting to land. Once that’s done we’ll be releasing v0.11.15 as a release candidate.

StrongLoop’s blog has a related post about their position on a major Node fork called io.js:

As it has been widely reported, last week a fork of Node went live called io.js. Io.js represents a technical exploration by key developers in the Node core community with the intent to accelerate the release of recent technical innovations, many of which were developed by StrongLoop developers.

At StrongLoop, we’ve always participated in leadership, advisory and technical efforts in the Node ecosystem when appropriate and will continue to do so. We actively play a role in the Node Advisory Board established by Joyent in October 2014.

Although this sounds like StrongLoop is endorsing Node for now, the author indicates that StrongLoop remains open to changes in the future:

We will continue to recommend the version that currently has the best community support, is most compatible with the tools and frameworks we develop and that we can support for our customers. Of course, our preference over time is to support a version that satisfies these requirements and adheres to an open governance model.

There’s an article on Wired that quotes Mikeal Rogers citing Joyent’s control as a reason for the fork:

“We don’t want to have just one person who’s appointed by a company making decisions,” says Mikeal Rogers, a Node community organizer involved in the fork. “We want contributors to have more control, to seek consensus.”

Of course other contributing factors must be the perceived slow progress of the 0.12 release. It’s possible that io.js will exist as a novel fork that influences mainstream Node, or it could be like Chrome vs. previous less popular WebKit browsers. My advice is to follow both and avoid judging either too soon.

Tweene, JSON Forms

04 Dec 2014 | By Alex Young | Comments | Tags libraries animation json forms

Tweene

Tweene (GitHub: SkidX/tweene, License: Artistic License 2.0, npm: tweene, Bower: tweene) by Federico Orrù is an API that wraps around popular animation libraries so you can switch implementation more easily. Rather than having to worry about whether you need to use translateX or just x, you can use Tweene’s API instead.

These are the supported libraries right now:

To create animations, you have to make tween instances using Tweene, and then call methods that set the duration and easing. It actually has several API styles based on GASP, jQuery, and Velocity, but I prefer the fluent API:

Tweene.get($target)
  .to({ opacity: 0, left: '+=50px' })
  .duration(500)
  .easing('easeOutQuad')
  .on('complete', completeCallback)
  .play();

The documentation for Tweene is detailed, and there are some examples on CodePen.

jQuery JSON HTML Forms

Cezary Wojtkowski sent in jquery-html-json-forms, a project that aims to support the W3C HTML JSON form submission specification:

This specification defines a new form encoding algorithm that enables the transmission of form data as JSON. Instead of capturing form data as essentially an array of key-value pairs which is the bread and butter of existing form encodings, it relies on a simple name attribute syntax that makes it possible to capture rich data structures as JSON directly.

This basically means you can use an enctype attribute of application/json in forms. This makes it a lot easier to create forms that send data to JSON APIs, rather than using the standard form encoding.

Cezary’s project allows you to use enctype='application/json' and then get JSON out with $(formElement).JSONencode(). You can also enable and disable the plugin.

The HTML JSON form specification is new to me, but it seems really cool for those of us who create lots of JSON APIs.

Node Roundup: Mailman, trayballoon, unembed

03 Dec 2014 | By Alex Young | Comments | Tags node libraries modules email windows scraping

Mailman

Mailman (GitHub: vdemedes/mailman, License: MIT, npm: mailman) by Vadim Demedes is a module for sending emails that supports generators. It uses nodemailer for sending email, and consolidate.js for templates, which means it supports lots of different template languages.

Generators are used for sending emails, so you can do this:

var mail = new UserMailer({ to: 'vadim@example.com' }).welcome();
yield mail.deliver();

Mailman expects a specific directory layout for views, but the added level of structure might help if you’ve got a big mess of email-related code in your current projects.

trayballoon

trayballoon

trayballoon (GitHub: sindresorhus/trayballoon, License: MIT, npm: trayballoon) by Sindre Sorhus is a module for showing system tray balloons in Windows. You can set the text and image to display, and a callback that will run when the balloon disappears:

trayballoon({
  text: 'Unicorns and rainbows'
  icon: 'ponies.ico',
  timeout: 20000
}, function() {
  console.log('Trayballoon disappeared');
});

It also has a command-line tool which you could use to display notifications when things like tests fail. trayballoon works by bundling an executable called nircmdc.exe which is called with child_process.spawn.

unembed

Given some “embed code” for sites like YouTube and Vimeo, unembed (GitHub: colearnr/unembed, License: MIT, npm: unembed) by Prabhu Subramanian will extract the markup and produce a JSON representation. This might be useful if you’re scraping sites that use embed codes, like blogs and forums.

I’ve never thought of applying the tiny modules philosophy to scraping, but it seems like a great way of sharing all of those hacks we use to extract data in a more structured way.

Why You Should Donate to Mozilla

02 Dec 2014 | By Alex Young | Comments | Tags community mozilla

Firefox donations

Recently Firefox prompted me to donate to Mozilla. The ad appeared on the Firefox Start Page, but you might not always see it – sometimes there’s a message that reads “Let the world know you #ChooseIndependent with Firefox.” I switch between browsers for testing quite a lot, so I’m not particularly tied to one browser. However, that day I’d been using the latest Firefox and the Firefox Developer Edition, so I was in a good mood about Mozilla and decided to donate a few dollars.

I happen to think that you should donate as well, and here’s why. The Mozilla Foundation has been involved with some projects that have been immensely useful and powerful: Firefox, PDF.js (Mozilla Labs), asm.js, and Rust spring to mind. Take a look at the Mozilla Research Projects list for more.

Something that JavaScript developers can’t live without is the Mozilla Developer Network documentation. I almost felt like I was donating to support that site alone!

Like you I also use Chrome, and I actually like Google’s email indexing and Google Now – the way it shows delivery information for recent purchases is awesome. So I’m not pro-Firefox due to any privacy issues. And Safari is totally gorgeous on Yosemite. It definitely feels like Firefox’s competition is strong, and the mainstream technology press is down on Firefox. The last few releases have felt as fast as Chrome though, and the UI is evolving to something clean and minimalist that I like.

I think Mozilla does a lot for us JavaScript developers. If you’d like to donate, go to sendto.mozilla.org. There’s also a FAQ about donations. You can now even donate bitcoin!

JavaScript Developer Survey 2014

01 Dec 2014 | By Alex Young | Comments | Tags community surveys

Here is the JavaScript Developer Survey for 2014! You have two weeks from now to complete the survey (the 15th of December).

I asked for help with the questions last year, and collected pull requests and issues to improve the survey. You can view the survey repository at alexyoung/dailyjs-survey. Many thanks to everyone who has helped so far.

Please fill out the survey and share it with your fellow JavaScript programmers! I make sure the data is open so it’s not just used for planning DailyJS content, you can use it as well.

Here’s the survey link again: JavaScript Developer Survey for 2014

The survey is now closed.

Mermaid: Like Markdown for Diagrams

28 Nov 2014 | By Alex Young | Comments | Tags svg libraries diagrams

Mermaid

When I work on books my editor always seems to push for more diagrams. Diagrams are useful, but drawing tools are a chore to use. When I get really stuck I resort to pen and paper or ASCII art. Writing suffers from the same issue: people love playing with writing tools and fonts before realising writing in Markdown or something similar is far more productive.

That’s why I thought Mermaid (GitHub: knsv/mermaid, License: MIT, Bower: mermaid) sounded cool:

Generation of diagrams and flowcharts from text in a similar manner as markdown.

Ever wanted to simplify documentation and avoid heavy tools like Visio when explaining your code?

This is why mermaid was born, a simple markdown-like script language for generating charts from text via javascript.

Rather than playing with stroke styles and colours, fonts, and other distractions, you can focus on the meaning the diagram is trying to encapsulate. Mermaid does allow you to include styles so you can change fill colours and strokes, but the text-based syntax might be easier to work with than GUI drawing tools under some circumstances.

I noticed Mermaid has two Jison files, which seems like a sensible way to parse the diagram syntax. For example, flow.jison is used to generate the parser that parses text graph definitions.

d3 is used for drawing, so you should be able to use Mermaid anywhere you use d3. It comes with a Gulpfile for generating optimised builds, and there are some Karma tests as well.

Material Design's Delightful Details with SVG Morpheus

27 Nov 2014 | By Alex Young | Comments | Tags animation svg libraries

SVG-Morpheus

SVG Morpheus (GitHub: alexk111/SVG-Morpheus, License: MIT, Bower: svg-morpheus) by Alex Kaul is a library for morphing between SVG icons. It implements the delightful details transition, as described by Google’s material design documentation:

The most basic use of animation is in transitions, but an app can truly delight a user when animation is used in ways beyond the obvious. A menu icon that becomes an arrow or playback controls that smoothly change from one to the other serve dual functions: to inform the user and to imbue your app with a moment of wonder and a sense of superb craftsmanship. Users do notice such small details.

You might have noticed this in Android recently: the first-party Android apps now have a nice transition for the back icon. This is visible in the Play Store app, for example.

Alex’s library allows you to do this with SVG icons, so you can employ the same effects in your web apps. All you need to do is add an SVG icon set to a document, then instantiate SVGMorpheus:

var myIcons = new SVGMorpheus('#myIconSet', options, callback);
myIcons.to('icon1');

The options include easing and duration, so you get some control over the transition.

The project’s documentation has more details on the API and the expected markup structure.

PowerArray, Atomus

26 Nov 2014 | By Alex Young | Comments | Tags array testing libraries modules

PowerArray

PowerArray (GitHub: techfort/PowerArray, License: BSD) by Joe Minichino is a small library that attempts to replace native Array methods with faster ones. You can use PowerArray.prototype.forEach to iterate over values using a simple for loop, which is known to be faster than Array.prototype.forEach. However, it also includes PowerArray.prototype.binarySearch which performs a binary search on the array.

Thanks to Oliver Caldwell’s post for a quick version of the algorithm. Also note the contribution of Yehonatan and other authors of comments to the post which helped to optimise the implementation of binary search further.

Oliver wrote this about the binary search algorithm:

A binary search searches by splitting your array into smaller and smaller chunks until it finds your desired value. Unlike the normal indexOf which searches from left to right in a simple iteration. The binary search Wikipedia article explains it best (as always). There are a couple of downsides; It will be slower with smaller data sets (this needs proving) and the array you are searching needs to be sorted.

To use the binary search you’ll need to sort the array first, and there’s PowerArray.prototype.numericSort which just uses Array.prototype.sort with return a.id < b.id ? -1 : 1.

The project includes some benchmarks so you can try it out for yourself.

Atomus

Everytime I use a Node/DOM testing library my tests seem to suffer from bitrot and stop working after a few months. So I was glad to see a new one by Krasimir Tsonev called Atomus (GitHub: krasimir/atomus, License: MIT, npm: atomus). It’s based on jsdom, so you get a window object and browser instance that lets you trigger events like clicked and blurred.

The following snippet is taken from the bundled AngularJS test:

var b = atomus()
.html('<html><body><div ng-controller="Controller"><register-form></register-form></div></body></html>')
.external(__dirname + '/data/angular.js')
.external(__dirname + '/data/angular.register-form.js')
.ready(function(errors, window) {
  if (errors !== null) console.log(errors);

  var Controller = function($scope) {
    var runTests = function() {

      var register = b.$('#register-button');
      var message = b.$('#message');
      var username = b.$('#username');
      var password = b.$('#password');

      b.clicked(register);

      assert.equal(message.text(), 'Missing username.');

The b.clicked(register) line causes the #register-button element to be clicked, and then there are some standard Node assert calls to ensure the document was updated as expected.

I’ve used other libraries like this, including Zombie.js. They all work in a slightly different way – Zombie.js also uses jsdom but some use PhantomJS or drive browsers with Selenium. It’s worth trying a few out to see what works for your project.

Paperclip.js, bem-react

25 Nov 2014 | By Alex Young | Comments | Tags templates reactive react

Paperclip.js

Paperclip (GitHub: mojo-js/paperclip.js, License: MIT, npm: paperclip) by Craig Condon is a template engine that’s a bit like React, except it translates HTML templates into JavaScript document fragments rather than using a virtual DOM. The template is then cloned when it’s used, and requestAnimationFrame is used to prevent unnecessary DOM operations.

Craig provided some examples so you can see how it compares to other projects:

Paperclip has been used for two years in production at ClassDojo, so it sounds battle tested. It has unit tests that run in browsers and Node, and you can also use the module itself in Node.

bem-react

bem-react (GitHub: dfilatov/bem-react, License: MIT, Bower: bem-react, npm: bem-react) is a module for React that provides features to support the BEM methodology which was developed by Yandex.

BEM is a methodology of web projects development, that allows you to divide an interface into logically independent blocks. At the same time BEM contains specific tools for the typical web developers’ tasks automatization. And finally BEM gives us opportunity to create libraries of web-components for fast and efficient web-development.

With this module, you can use “bemjson” in templates instead of jsx or JavaScript, and manipulate CSS classes based on BEM.

I noticed there’s a demo app in bem-react/example that highlights the bemjson special fields, component use, and component composition.