Ractive.js, Japanese DailyJS Translations

Ractive

Ryan McDonough sent in Ractive.js (GitHub: Rich-Harris/Ractive, License: MIT, Bower: ractive), a new alternative to libraries like AngularJS, created by developers at The Guardian. Are we still calling these libraries MVC, MV*, or something else?

Ractive.js is different. It solves some of the biggest headaches in web development - data binding, efficient DOM updates, event handling - and does so with almost no learning curve.

There’s a nice and short example in the documentation. Given the following HTML fragment:

<p>Hello ! You have
    <strong> new messages</strong>.
</p>

Then the Ractive constructor can be used to populate data:

var ractive = new Ractive({
  el: result,
  template: html,
  data: {
    user: 'Dave',
    messages: { total: 11, unread: 4 }
  }
});

ractive.set('messages.unread', 5);

However…:

Ractive.js constructs a parallel DOM representation which is aware of its dependencies on the values of user and messages.unread. When those values change, it knows exactly which parts of the real DOM need to be updated.

This could be the data-binding library with an idiomatic JavaScript API that we’ve been looking for. By focusing on the “data model” problem the project seems immediately easier to understand than some larger libraries, and the early adoption of Bower and Grunt means it should be straightforward to slot into your projects.

Japanese DailyJS Translations

Hideharu Sakai sent in his translation of my recent “Getting started with Nodebots” article: Nodebot を始めよう(著者:アレックス・ヤング). He said there’s a lot of interest in Node and DailyJS from the Japanese developer community, so thanks for that!

Getting Started with Nodebots

25 Jul 2013 | By Alex Young | Comments | Tags node modules robots nodecopter arduino
Hey, laser lips, your mama was a snow blower The johnny-five module, with art by Mike Sgier.

I’ve been collecting lots of resources relating to Arduino, Node, and robots, and there seems to be a lot of interest in the Node community around Arduino and quadcopters. The jewel in the crown of electronics-related Node modules is johnny-five (GitHub: rwldrn / johnny-five, License: MIT, npm: johnny-five. This Arduino programming framework from Bocoup provides an event-based interface into Arduino boards. The readme includes links to a wealth of examples written using JavaScript, embedded in Markdown with documentation and images. For example, Nodebot is a simple robot with motors and wheels that starts a REPL that allows you to move the robot around with commands like n.left.

Arduino works by accepting code over USB – it comes with an IDE derived from Processing which does all of that for you. In johnny-five projects, the serialport module by Chris Williams (voodootikigod) makes getting code onto your electronic creations possible. Chris has been involved with the world of Node and Arduino since 2010. The serialport module requires native compilation – the readme has instructions for Windows, OS X, and Linux.

Imagine a world where you can write JavaScript to control blenders, lights, security systems, or even robots. Yes, I said robots. That world is here and now with node-serialport. It provides a very simple interface to the low level serial port code necessary to program Arduino chipsets, X10 wireless communications, or even the rising Z-Wave and Zigbee standards. The physical world is your oyster with this goodie.

The API is event-based, so if you’re familiar with Node’s asynchronous core modules then you should be able to learn it pretty quickly. There are alternatives to johnny-five as well: duino by Cam Pedersen seems fairly mature.

NodeCopter

The nodecopter-remote module can be used to script flying drones. It’s built with johnny-five, and is popular with attendees of the NodeCopter.js events:

NodeCopter.js is a full day event where 15 - 60 developers team up in groups of 3.

Each team receives one Parrot AR Drone 2.0 and spends the day programming and playing with it. At the end of the day, each team gets to present their work to the other attendees.

I was introduced to NodeCopter.js by Andrew Nesbitt, who has spoken about Node and quadcopters at events in the UK, and organised Nodecopter London back in March.

There are a lot of other related modules on npm categorised under nodecopter – one particularly fascinating one is voxel-drone which is an AR Drone simulator in voxeljs.com.

Getting Hardware

There are a lot of cheap Arduino kits around now. The johnny-five documentation mentions the SparkFun Inventor’s Kit which is no longer available, but can be found in certain stores (I got one from Amazon a few months ago). The page for the kit has a list of the included parts, so you could order the ones you want separately.

All you really need is an Arduino board, but the important thing is the microcontroller – you can use other boards with the same or compatible microcontrollers. Even better: Arduino is open, so you can build your own boards.

If you’re not sure about Arduino but have access to a Raspberry Pi or BeagleBone, then you could try bonescript:

Bonescript is a node.js library for physical computing on embedded Linux, starting with support for BeagleBone.

The Raspberry Pi is more like a full-blown PC, but it has a simple hardware interface that does digital and analogue I/O – meaning you can connect it to sensors and motors. I managed to wire mine up to an IR sensor from a defunct laptop to make Raspbmc work with my TV remote.

If you’re hooking up hardware with Node, let me know in the comments and I’ll check out your projects!

Node Roundup: Magnolia, VMUX, joinr

24 Jul 2013 | By Alex Young | Comments | Tags node modules mongodb video webrtc
You can send in your Node projects for review through our contact form.

Magnolia

Ryan Munro sent in some of his projects, including Magnolia (GitHub: Submersible / node-magnolia, License: MIT, npm: magnolia) and Figs (GitHub: Submersible / node-figs, License: MIT). Magnolia is a MongoDB client library that has a chainable API and support for promises, which means you can compose expressions using a natural JavaScript-friendly syntax.

magnolia('user')
  .filter({_id: ObjectID('4e4e1638c85e808431000003')})
  .one()
  .then(function(user) {
      console.log('hello', user.name);
  });

Figs is a module for working with settings stored in JSON files. It supports local overrides, “parent directory clobbering”, and overriding when environmental variables are set. It also includes a command-line tool for viewing configurations.

VMUX

VMUX

VMUX (GitHub: malditogeek / vmux, License: BSD) by Mauro Pompilio is an open source video call application that works in browsers, and uses Node. Nodejitsu wrote about it as part of their open source project of the month programme. The readme includes details on how to set it up locally, but you can also try out the service running on Nodejitsu by signing in with Twitter.

Nodejitsu’s blog has had a flurry of activity recently, including a cool post about GUI console applications.

joinr

There is another MongoDB module this week that I wanted to write about: joinr (GitHub: punkave / joinr, License: MIT, npm: joinr) by Tom Boutell. This one fetches related documents by performing join-related operations:

joinr allows joins to be performed via IDs stored in a regular property (byOne) or in an array property (byArray). Joins can be performed when the ID of the related document is in the document you already have (byOne or byArray) and also when the related documents contain the IDs of documents you already have (byOneReverse and byArrayReverse).

For example, a one-to-many join through an array property looks like this:

joinr.byArray(users, 'groupIds', '_groups', function(ids, callback) {
  return groupsCollection.find({ groupIds: { $in: ids } }, callback);
}, callback);

There are more examples in the readme.

jQuery Roundup: Audio Sort, Improving fn.on with Generic Function Overloading

23 Jul 2013 | By Alex Young | Comments | Tags jquery plugins ideas audio sort
Note: You can send your plugins and articles in for review through our contact form.

Audio Sort

Audio Sort

I’ve had a difficult week of dealing with Windows 8, IE, and Visual Studio, so forgive me if I don’t indulge myself a little bit by writing about Audio Sort (GitHub: skratchdot / audio-sort, License: MIT). It’s written by “skratchdot” and is a visualisation of sort algorithms using jQuery, D3.js, subcollider.js, and Bootstrap.

When it comes to sort visualisations, I don’t think anything will beat Quick-sort with Hungarian folk dance (thanks Matias) for sheer eccentricity, but it’s a solid piece of work, and the inclusion of sound is somewhat idiosyncratic.

In a previous life I was also interested in audio programming, and subcollider.js is new to me. If you’ve ever seen SuperCollider but prefer JavaScript’s syntax then you may enjoy it.

Improving fn.on with Generic Function Overloading

Sergii Kliuchnyk sent in js-fn-overloading:

I looked at the code for the Jquery.fn.on method and realized how many methods they have which take different argument types. They do many checks to change argument values to the right types. Here’s my proposition for how to make the code clearer: js-fn-overloading and here’s an example of what Jquery.fn.on looks like with it: jqueyr-on.js

The example in the readme is quite straightforward:

var obj = {
  func: Overload('{Object|String}event, {String}[selector], {*}[data], {Function}fn', function(event, selector, data, fn){
    ok(this === obj);
    ok(typeof event === 'object' || typeof event === 'string');
    ok(typeof selector === 'undefined');
    ok(typeof data !== 'undefined');
    ok(typeof fn === 'function');
  });
};

obj.func('', 1, function(){});

The Overload function takes a configuration string which determines what types the overloaded methods should support, and how they should be mapped to arguments.

RgbQuant, Scoping AngularJS Directives

22 Jul 2013 | By | Comments | Tags images libraries browser AngularJS

RgbQuant

RgbQuant

RgbQuant (GitHub: leeoniya / RgbQuant.js, License: MIT) by Leon Sorokin is an image quantization library that runs in browsers:

Color quantization is the process of reducing an image with thousands or millions of colors to one with fewer (usually 256). The trick is to balance speed, cpu and memory requirements while minimizing the perceptual loss in output quality. More info can be found on wikipedia. Various algorithms can be found on rosettacode.org.

Internally it uses typed arrays, some ES5 array methods, and a Canvas element. The API allows the number of colours to be defined, and some more low-level control over the algorithm.

Scoping AngularJS Directives

James Donaghue sent in his articles about scoping AngularJS directives: Scoping AngularJS Directives Part 1 and Scoping AngularJS Directives Part 2.

… when both are applied to the same element, regardless of order, they have the same scope which is the scope type 3 (isolated scope). This is the most important combination to understand as you other directives may be expecting either direct or prototypical access to the nearest controller scope, but when paired with an isolated scope directive they no longer have this access. This can lead to many unexpected errors. In my opinion isolated scopes should be used only very judiciously and with exact intention understanding this behavior.

Feaxures, RBush, Bootstrap Modal

19 Jul 2013 | By Alex Young | Comments | Tags libraries modules bootstrap node ui

Feaxures

Feaxures

Feaxures (GitHub: adrianmiu / feaxures, License: MIT) by Adrian Miu is a progressive enhancement library that combines ideas from the DRY principle, responsive design, A/B testing, and RequireJS:

RequireJS is used to handle the process of loading asyncronously the JS/CSS files. It also helps with managing the depencies. For example if the jquery.ui.tabs.js file is dependent on jquery.ui.widget.js file, RequireJS will load that file first, assuming you have configured it properly using the shim option.

Once you’ve configured your RequireJS loader script, data attributes prefixed with data-fxr- are used to tie specific features to blocks of markup. The attribute’s value can be set to several things including URL query strings, JSON, and DOM IDs to pass options to the feature.

The Feaxures API also has lifecycle events so you can see when features are loaded and attached.

RBush

RBush (GitHub: mourner / rbush, License: MIT, npm: rbush) by Vladimir Agafonkin is a high-performance 2D spatial indexer for points in rectangles:

Spatial index is a special data structure for points and rectangles that allows you to perform queries like “all items within this bounding box” very efficiently (e.g. hundreds of times faster than looping over all items). It’s most commonly used in maps and data visualizations.

Trees can be created and values subsequently inserted like this:

var tree = rbush(9, ['.minLng', '.minLat', '.maxLng', '.maxLat']);
tree.insert({id: 'foo', minLng: 30, minLat: 50, maxLng: 40, maxLat: 60});

Data can also be inserted in bulk by using arrays, and values can be searched, removed, and exported. It also works in browsers. The readme has some interesting papers related to r-trees, and Vladimir has included unit tests written with Mocha.

Bootstrap Modal

Bootstrap Modal (GitHub: cabaret / bootstrap-modal-strict-close, License: Apache 2.0) by Joris Ooms is a small extension to Bootstrap’s modal dialog to prevent it from being accidentally closed when triggering actions like form submission.

Use it by adding the attribute data-strict-close="true" or passing strictClose: true to the .modal method’s options.

AngularJS: Installation

18 Jul 2013 | By Alex Young | Comments | Tags angularjs angularfeeds mvc bower

I’ve been working on tidying up the AngularJS tutorial project, which you can find here: GitHub: alexyoung / djsreader. The project was originally created with Yeoman, as part of the topics I wanted to cover on the tutorial series. However, a fresh checkout of my code from GitHub wouldn’t run out of the box, so I wrote up some instructions in the readme.

Although I’d prefer it if people could follow the tutorial series from part 1 and build their own version, it’s not always possible as dependencies change over time. I get asked about this a lot, and it’s just a consequence of the style of tutorials I write on this blog. It would be nice if I could maintain these articles and keep them working with the latest version of each of the major dependencies, but I have to earn a living!

If you just want to check out the AngularJS tutorial source and play with it I’ve included instructions below.

Installing the Dependencies

To run the project, you’ll need to install the following things:

  • Node 0.10.x
  • Bower (npm install -g bower)
  • Grunt (npm install -g grunt-cli)
  • Compass (gem install compass)

Hopefully you already have Node – which means Bower and Grunt should be easy to install. Compass is annoying: one of the Grunt tasks builds Bootstrap from Sass, which needs the command-line compass Ruby script. It’s annoying because Ruby is a mess and unless you work with it professionally you really don’t want to have to deal with Ruby version management. Fortunately, I found gem install compass on a fresh Mountain Lion machine worked out of the box. The Ruby version is 1.8.7, which is dated. I noticed sudo gem install compass resulted in a script that wouldn’t work and I didn’t bother to find out why. I may replace the Grunt task to get rid of this dependency so we can just depend on Node.

Once you’ve got that installed, npm install will fetch Grunt’s dependencies. Then run bower install to get the client-side libraries.

Using and Running It

The gruntfile that Yeoman generated has a few goodies built in. You can build the project with grunt build, run tests with grunt test, and start a server with grunt server – this is the one you probably want, and if things don’t seem to work in the browser just check you’ve built it first.

Hacking It

If all you want to do is try out some AngularJS ideas or change the HTML, you should familiarise yourself with the project tree. Most of what you want is in app/, and in particular app/scripts/controllers/main.js is what most of the tutorials refer to and app/views/main.html is the corresponding template.

Now you should be able to run the project without following the individual tutorials. Hopefully newcomers can at least try the project out relatively painlessly.

Node Roundup: 0.11.4, NodeICO, Node-FSAPI

17 Jul 2013 | By Alex Young | Comments | Tags node modules http restify services
You can send in your Node projects for review through our contact form.

Node 0.11.4

Node 0.11.4 was released last week. The major dependencies have been upgraded (npm, v8, c-ares), and there’s a change in behaviour for timers: setImmediate has been changed to process the full queue on each turn.

There are also other tweaks and improvements for HTTP, buffer, stream, crypto, and zlib. The brief fluffy of work on HTTP involved new Agent code and fixed keepAlive behaviour.

NodeICO

NodeICO (GitHub: rvagg / nodei.co, License: MIT +no-false-attribs) is an open source service that displays badges for Node modules. As an example, this is what the Express badge looks like:

There’s also a cool graph version:

The project was written by Rod Vagg and uses restify.

Node-FSAPI

Speaking of restify, Kent Safranski sent in Node-FSAPI (GitHub: Fluidbyte / Node-FSAPI), which is a project to provide a RESTful server for interacting with remote file systems. It supports three layers of security: URL keys, IP restriction, and HTTPS.

The client implementation supports Ajax, so from what I can tell you could use it as a browser-based solution for storing files.

jQuery Roundup: Queuing Ajax Requests, imagefill.js, Feedback Me

16 Jul 2013 | By Alex Young | Comments | Tags jquery plugins ajax backbone.js images forms widgets
Note: You can send your plugins and articles in for review through our contact form.

Queuing Ajax Requests

In Queuing Ajax Requests in JS Web Apps, Alex MacCaw talks about how to queue requests with jQuery.ajax and safely retain the sequence of operations generated by Backbone and Spine applications.

We still have a problem if a particular request fails, as the interface will now be out of sync with the database. I usually recommend treating this as an exceptional circumstance, and prompt the user to reload the page. Incidentally, this is exactly how Facebook and Twitter solve the problem.

The plugin can be used like this: jQuery.ajax({type: 'POST', queue: true}), and is available as a Gist at maccman / jquery.ajax.queue.coffee.

He’s also recently published Memory Management in JS Web Apps, which discusses how to properly clean up Backbone and Spine controllers when DOM elements are removed using jQuery’s special events.

imagefill.js

imagefill.js (GitHub: johnpolacek / imagefill.js, License: MIT/GPL) by John Polacek is a jQuery plugin for making images fill their containers. It can be configured to run once, or throttle the frequency at which container sizes are checked. The author suggests this plugin could be useful for creating responsive sites.

Feedback Me

Feedback Me (GitHub: vedmack / feedback_me, License: MIT, jQuery: feedback_me) by Daniel Reznick is a UI widget that shows a feedback form that appears from the side of a page. It is designed to work out of the box with jQuery UI and Bootstrap, and includes allows each label in the feedback form to be configured.

Reddit Insight, dropstore-ng

15 Jul 2013 | By Alex Young | Comments | Tags node mongodb express apps AngularJS

Reddit Insight

Reddit Insight

Patrick Stapleton sent in Reddit Insight (GitHub: gdi2290 / RedditInsight, License: MIT), a project for tracking and visualising statistics about reddit. It can track posts, users, and display interactive charts for words and topics. There’s also a frequency analysis of nouns, and a graph for comments per-post and average karma per-post.

If you want to install it, check the code out from GitHub and install the Node dependencies:

git clone https://github.com/gdi2290/RedditInsight.git
cd RedditInsight
npm install

If you don’t have nodemon installed you can install that too – the authors use it to automatically reload the code when server-side code changes:

npm install -g nodemon
npm start

I haven’t yet figured out where they got the data from – the post and user trackers call reddit’s APIs, but the clusters have locally cached JSON files.

dropstore-ng

dropstore-ng

More AngularJS bindings! dropstore-ng by Jason Kulatunga is a wrapper around Dropbox Datastore. Dropbox’s API has bindings for iOS, Android, and JavaScript – this library allows you to fit it into an AngularJS-style workflow. You can DI it, authenticate with Dropbox, then add datastore items to the current $scope:

...
.then(function(datastore){
  var taskTable = datastore.getTable('tasks');
  $scope.tasks =  taskTable.query();
});

And display them as you might expect:

<ul>
  <li ng-repeat="task in tasks">
    
  </li>
</ul>

I haven’t yet used the Dropbox Datastore API, but this looks like idiomatic AngularJS to me. There are no directives as far as I can see, but I can’t think of any that would make sense…

Luc, z.js, Tabler

Luc

Luc (GitHub: pllee / luc, License: MIT, npm: luc) by Patrick Lorian Lee is a framework written in ECMAScript 5 designed to work with browsers and Node. It includes classes for working with arrays, dates, functions, events, and some high-level architectural tools.

For example, this is the composition API, which allows functionality to be added to classes while respecting the inheritance chain:

var C = Luc.define({
  $compositions: {
    defaults: Luc.compositionEnums.EventEmitter,
    methods: ['emit']
  }
});

var c = new C();

typeof c.emit
>"function"
typeof c.on
>"undefined"

Classes can be created with Luc.define:

var C = Luc.define({
  init: function() {
    Luc.Array.each(this.items, this.logItems)
  },

  logItems: function(item) {
    console.log(item);
  }
});

var c = new C({items: [1,2,3]});
>1
>2
>3
var d = new C({items: 'A'});
>'A'
var e = new C();

The array functions can be found under Luc.Array – it has the kinds of methods you might be familiar with from libraries like Underscore. The method signatures are similar as far as I can tell: Luc.Array.findFirst([1,2,3, {}], {});.

Luc’s source has JSDoc-style comments, a Grunt build script, and unit tests. It has no dependencies and is currently around 650 lines of code.

z.js

z.js (Source: z.js, License: MIT) is a tool for turning text into a binary code that uses zero width non-breaking spaces. That means you can create invisible messages that work in most modern browsers (including IE8+). It can even apply a password to the message so potential snoops must go through an extra level of misdirection.

There’s even an ASCII mode where tabs and spaces are used instead of UTF8.

Tabler

I really loathe making tables, yet almost every project seems to need them. I inevitably end up creating or finding a table generator that can turn data into suitable HTML tables. Tabler (GitHub: BrandwatchLtd / tabler, License: MIT) by Steve Mason is an AMD-friendly, Mocha-tested library for building dynamic tables. It takes an array then generates tables based on a “spec” – a definition of the headers and properties to include in the output. Usage looks like this:

var table = tabler.create([
    {field: 'name', name: 'Name'},
    {field: 'apples', name: '# Apples'},
    {field: 'bananas', name: '# Bananas'}
]);

table.load([
    {name: 'Steve', apples: 2, bananas: 4},
    {name: 'Graham', apples: 1, bananas: 6},
    {name: 'Dan', apples: 9, bananas: 2},
    {name: 'Jon', apples: 5, bananas: 6}
]);
table.render();

Review: Kodiak JavaScript

11 Jul 2013 | By Alex Young | Comments | Tags apps iOS reviews

Kodiak JavaScript (iTunes: Kodiak JavaScript, Price: $4.99) is an iOS IDE created by @becomekodiak, a group of developers that apparently really like bears.

Kodiak's file browser and editor views, and the sidebar.

This app comes bundled with over 50 libraries and frameworks familiar to JavaScript developers, and most of the features you might expect: syntax highlighting with various themes, a tabbed editor, a file navigator, and a preview mode that uses the built-in WebKit browser. It also supports Retina displays and external keyboards.

The settings panel allows the theme, font, and font size to be changed. I found DejaVuSansMono looked best. A preview is displayed in the same view so you can easily see what each option does.

The IDE settings and the impress.js demo being previewed.

I tried it out with some of the bundled libraries – impress.js for example worked fine, and I made a quick scratch project just to get a feel for the basics.

One of the best features in the app is the keyboard. Much like other text or terminal apps, it includes a bar with commonly used keys along the top. It has a button in the centre which can be used to move the cursor around easily, and the other keys have gesture-based punctuation shortcuts which are great for quickly inserting quotes and brackets.

Kodiak doesn’t like loading large files which I suspect is a limitation of their editor design – for your own files it should be fine, but if you try to open a 40 KB JavaScript library it’ll make the device slow down quite a bit. Also, large files can’t be edited, they open in a read-only mode instead.

I don’t remember VimTouch having limitations like that, but it’s a very different application. In fact, I think the strength of Kodiak JavaScript lies in its educational value – if you’re starting out learning JavaScript it could be a great companion application to a suitable Kindle/iBooks eBook.

I noticed that one of the Kodiak developers has a GitHub account with some polished-looking Objective-C projects: Adam Horacek. This includes the cool keyboard found in the Kodiak apps, which is KOKeyboard. Adam’s work is definitely worth taking a look at if you do any iOS development.

Node Roundup: 0.10.13, Node Linux, Tree Model

10 Jul 2013 | By Alex Young | Comments | Tags node modules trees data-structures linux
You can send in your Node projects for review through our contact form.

Node 0.10.13

Node 0.10.13 was released yesterday. Updates include libuv, npm, and fixes for the following core modules: tls, http, zlib, and buffer.

Node Linux

Corey Butler sent in node-linux (GitHub: coreybutler / node-linux, License: MIT, npm: node-linux), which is a follow up to node-windows and node-mac. The Mac and Windows versions provided an integration layer for working with OS-specific features like event logging and service management. The Linux version creates System V init.d files that run Node scripts and daemons.

The author is planning to add systemd and upstart script generation, and notes in the readme that he’d like contributions in those areas if possible.

tree-model-js

tree-model-js

tree-model-js (GitHub: joaonuno / tree-model-js, License: MIT, npm: tree-model) by Joao Nuno Silva is a module for manipulating and traversing tree-like structures. It’s available for Node, but also supports browsers and AMD.

Trees can be defined with a JSON-friendly syntax:

var tree = new TreeModel();
var root = tree.parse({
  id: 1,
  children: [{
      id: 11,
      children: [{id: 111}]
    }, {
      id: 12,
      children: [{id: 121}, {id: 122}]
    }, {
      id: 13
    }
  ]
});

Nodes can then be traversed with .walk, removed with .drop, and added with .addChild.

jQuery Roundup: Selleckt, Drag and Drop AngularJS, jqfactory

09 Jul 2013 | By Alex Young | Comments | Tags jquery plugins jqueryui widgets angularjs select
Note: You can send your plugins and articles in for review through our contact form.

Selleckt

Selleckt (GitHub: BrandwatchLtd / selleckt, License: MIT) by Graham Scott is another select replacement. This one comes with Mocha tests, multiple select support, mustache.js for templating, and works as an AMD module or jQuery plugin.

The basic syntax (taken from the demo page) looks like this:

$select3.selleckt({
  mainTemplate: fancyTemplate,
  selectionTemplate: selectionTemplate,
  selectedClass: 'selected',
  selectedTextClass: 'selectedText',
  itemsClass: 'items',
  itemClass: 'item'
});

There are tonnes more options which are documented in the project’s readme on GitHub.

Drag and Drop for AngularJS

Drag and Drop for AngularJS (GitHub: codef0rmer / angular-dragdrop, License: MIT) by Amit Gharat is an AngularJS directive for jQuery UI’s Draggable Widget.

It supports draggable items and droppable targets, and activity can be observed using a controller’s $scope. The markup for the relevant directives looks like this:

<div class="btn btn-primary" data-drag="true" data-jqyoui-options="{revert: 'invalid'}" ng-model="list1" jqyoui-draggable="{animate:true}" ng-hide="!list1.title"></div>

The project comes with a Grunt build script and unit tests.

jqfactory

jqfactory (GitHub: gfranko / jqfactory, License: MIT) by Greg Franko is an API for building stateful jQuery widgets. It’s inspired by the jQueryUI widget factory, and supports jQuery prototype namespacing support, deferred/promises, clean event binding and clean up, and AMD.

The project’s readme contains a walkthrough that demonstrates how to wrap your code in Greg’s API. Here’s a snippet that shows how to support options, the constructor, and reinitialisation:

(function($, window, document, undefined) {
    // Your plugin will go here
    // namespace - person
    // name - greg
    $.jqfactory('person.greg', {
        // Your plugin instance properties will go here
        // Default plugin options
        options: {
            occupation: 'JavaScript Engineer',
            age: 24
        },
        // Plugin Constructor
        _create: function() {
            // This is where you can set plugin instance properties
            this.fullname = 'Greg Franko';
        },
        // Plugin re-initialized
        _init: function() {
            // You can include any logic that you like when your plugin constructor is re-called
        }
    }
    });
}(jQuery, window, document));

The project includes more documentation, a Grunt build script, and Jasmine tests.

Voyeur, Page Notes, Validator

Voyeur

Voyeur

Voyeur (GitHub: dunxrion / voyeur.js, License: MIT) by Adrian Cooney is a DOM traversal and manipulation library. It creates window.Voyeur, which wraps around document.body. Then Object.defineProperty is used to add getters to nodes that are accessed through Voyeur. That means Voyeur.element.child.child.fn() can be used to access elements and perform operations on them. Elements can be created with the same syntax.

Methods are provided for working with elements. For example, use allows several operations to be performed on the same element:

Voyeur.div.ul.li.use(function(li, i) {
  li.innerText = 'Hello';
});

Tags can be inserted by using the create method, and this can be combined with use:

Voyeur.ul.li.eq(3, 9).use(function(li, i) {
  li.create.em.innerText = 'Emphasized text!';
});

The author has included tests and a Grunt build script.

Page Notes

Page Notes (pagenotes.js, License: MIT) by Jim Williams is a client-side script for working with a flexible implementation of tooltips that support rich annotation-like styles:

Page notes are a very general, highly intuitive generalization of tooltips. When the mouse stops over a tooltip target, a target annotation is embedded in a tooltip skin and displayed according to a placement specification. The skin together with the placement specification constitute the tooltip template. And the resulting displayed tooltip is the page note. No user-supplied JavaScript is involved.

Since tooltips are HTML fragments, they can also contain tooltips, which allows the library to support nested annotations. Attributes are used to configure tootips. For example, placement can be used to position the container.

Validator

Validator (GitHub: Nijikokun / Validator, License: MIT, npm: schema-validator) by Nijiko Yonskai is a Node module with browser support that allows data to be validated using a simple JSON schema:

var schema = {
  username: {
    type: 'String',
    required: true,
    length: {
      min: 3,
      max: 36
    },
    test: /^[a-z0-9]+$/gi
  }
};

var validator = new Validator(schema);
var check = validator.check({
  username: 'Niji%kokun'
});

console.log(check);

The Validator constructor can return an object that will work as Express middleware, which allows routes to validate data and populate the req.validated property. New validators can be added using Validator.implement.

Primus, it.js, highcharts-ng

Primus

Primus

Primus (GitHub: 3rd-Eden / primus, License: MIT, npm: primus) by Arnout Kazemier is a wrapper for various popular real-time frameworks. It allows you to switch between SocketJS, Engine.IO, or Socket.IO.

The biggest problems always happen when you deploy your application to production servers. This is when they receive large quantities of traffic and small bugs can lead to major disasters. Wouldn’t it be nice to be able to switch between real-time servers when they are the source of your issues without having to rewrite your application?

It includes client-side hooks, so both your Node and browser-based code can be written independent of the underlying communication layer. The APIs are event-based, and documentation and tests have been included.

it.js

it.js (GitHub: dtinth / it.js, License: MIT, npm: it.js) by Thai Pangsakulyanont is a small functional library inspired by Q and Underscore for creating accessor and iterator callbacks. It’s chainable, which means you can do this:

It.get('first').get('length')

Instead of this:

function(person) { return person.first.length; }

Wrappers for boolean operators have been included, so your chains can include logic:

// these three are equivalent to function(x) { return !x.last }
console.log(_.select(addressBook, It.not(It.get('last'))));
console.log(_.select(addressBook, It.get('last').not()));
console.log(_.select(addressBook, It.not('last')));

highcharts-ng

highcharts-ng (GitHub: pablojim / highcharts-ng, License: MIT) by Barry Fitzgerald is an AngularJS directive for Highcharts. Barry says this demonstrates how easy it is to use third-party JavaScript with AngularJS. He’s posted an example on jsFiddle.

Here’s a snippet of how it looks just so you can see that it looks like idiomatic AngularJS code:

var myapp = angular.module('myapp', ['highcharts-ng']);

myapp.controller('myctrl', function($scope) {
  $scope.addPoints = function() {
    var seriesArray = $scope.chart.series
    var rndIdx = Math.floor(Math.random() * seriesArray.length);
    seriesArray[rndIdx].data = seriesArray[rndIdx].data.concat([1, 10, 20]);
  };

Getting Started with HBase and Thrift for Node

04 Jul 2013 | By Nathan Sweet | Comments | Tags node hbase thrift

Node and HBase

Why Node and HBase?

I think the title of this article is self explanatory, but for a bit of bit background for people who may not know: NodeJS is a JavaScript server framework based on a very thin and fast I/O multiplexer. That means NodeJS is great for things like proxying lots of short lived connections. Node’s abilities make it ideally suited for being a proxy to a high-write database like HBase.

Traditionally the way to communicate with HBase using Node is to use the REST interface. This is both slow and not ideally suited for a scaling production environment. If we could leverage the write-scale of HBase with the proxy-scale of Node we could do some pretty cool things, like script map-reduce jobs for HBase in JavaScript, or create a service to do low latency writes. How can we do this? The answer is Thrift!

What is Thrift?

Thrift is a “software framework, for scalable cross-language services development…with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js…” Thrift allows us to create a thin API in NodeJS to communicate with HBase using a thin socket protocol. The advantages over REST are that the connection stays alive and the protocol is thinner than XML.

Enough analysis, let’s get started.

Getting Started

First you will need to install HBase and Thrift. I’m not going to go over that here, as there are other great tutorials to do that. Here’s one for HBase and one for Thrift (you’ll need some other things to get Thrift going). Once you have both HBase and Thrift installed go ahead and open up your shell of choice and create a working directory and make it your current directory.

mkdir node_hbase
cd node_hbase

Then generate the Thrift files for Node like so:

thrift --gen js:node [hbase-dir]/src/main/resources/org/apache/hadoop/hbase/thrift/HBase.thrift

The tutorial for generating these files can be found here.

After generating these files it’s time to create our Node file. Here is an example that we can use. Make sure this file is inside the folder we created:

// This section includes a fix from here:
// https://stackoverflow.com/questions/17415528/nodejs-hbase-thrift-weirdness/21141862#21141862
var thrift = require('thrift'),
  HBase = require('./gen-nodejs/HBase.js'),
  HBaseTypes = require('./gen-nodejs/HBase_types.js'),
  connection = thrift.createConnection('localhost', 9090, {
    transport: thrift.TFramedTransport,
    protocol: thrift.TBinaryProtocol
  });

connection.on('connect', function() {
  var client = thrift.createClient(HBase,connection);
  client.getTableNames(function(err,data) {
    if (err) {
      console.log('gettablenames error:', err);
    } else {
      console.log('hbase tables:', data);
    }
    connection.end();
  });
});

connection.on('error', function(err){
  console.log('error', err);
});

We don’t want to run this yet. We need to start HBase and HBase’s Thrift server/API. Starting HBase is easy, it’s just one command:

[hbase-dir]/bin/hbase-daemon.sh start thrift -f

Now we can run our Node file. You may want to go into the HBase shell and create a table, otherwise you will get an empty array back from the example above.

The HBase Thrift API is documented here. The Node implementation of these methods will be different than how they are written and will almost never return anything, but instead will have a callback as an argument which will give the result of the method.

I think Node, HBase, and Thrift as a stack is a winning combination and would be ideally suited for something like a custom analytics platform or a mapping platform.

I will do my best to keep up with any comments or questions people have below (until they close).

Node Roundup: 0.11.3, Busboy, connect-mongostore, Chance

03 Jul 2013 | By Alex Young | Comments | Tags node modules html forms middleware testing sessions connect
You can send in your Node projects for review through our contact form.

Node 0.11.3

Node 0.11.3 was released last week, which was a fairly large update: libuv, c-ares, and v8 were all updated. The debugger now breaks on uncaught exceptions, and there were changes to enable dtrace for libuv’s probes (if enabled). The underlying implementation for buffers has undergone major changes as well – I’ve picked out a few commits here that discuss the updates:

It looks like these changes should make the buffer implementation more robust. I’ve checked out Node 0.11.x and 0.10.x on my local machine and run make bench-buffer against both, so far 0.11 doesn’t look conclusively faster, but I haven’t been particularly scientific about the process yet.

Busboy

Busboy (GitHub: mscdex / busboy, License: MIT, npm: busboy) by Brian White is a streaming HTML form data parser. It uses the Dicer module to parse multipart fields, and also uses a stream parser for urlencoded fields.

The busboy API allows limits to be placed on the incoming data. The Busboy constructor accepts an options object which may include a limits property. Limits can include fieldNameSize, fieldSize, files, and more – see the readme for full documentation. These options mostly default to Infinity, apart from fieldNameSize which is 100 bytes.

Tests are included, and it should be possible to use it as Express middleware fairly easily.

connect-mongostore

How do you decide which session middleware to use? Use cookies during early development then quickly search npm for something that uses your database? Me too! But there are better options out there and it’s worth taking a bit of time to research them. Ilya Shaisultanov sent in connect-mongostore (GitHub: diversario / connect-mongostore, License: MIT) which is an attempt to write a cleaner session store that takes advantages of features like replica sets, and has test coverage.

Chance

Chance

Chance (GitHub: victorquinn / chancejs, License: MIT, npm: chance) by Victor Quinn is a library for generating random stings, numbers, and even things that are useful for test data like address elements and names.

It works in browsers and Node, and has a simple constructor-based API:

var Chance = require('chance');
var chance = new Chance();
chance.name({ middle: true });

jQuery Roundup: minimit-anima, loda-button

02 Jul 2013 | By Alex Young | Comments | Tags jquery plugins icons animations css3
Note: You can send your plugins and articles in for review through our contact form.

minimit-anima

minimit-anima

minimit-anima (GitHub: minimit / minimit-anima, License: MIT, jQuery: minimit-anima) by Riccardo Caroli is an animation plugin that uses hardware accelerated CSS3 animations with fallbacks for older browsers. The API is queue-based like jQuery’s standard animation API. The following example specified an easeOut of 400ms:

$(this).anima({ x: 20, y: 20 }, 400);

Hardware acceleration can be triggered by adding the z co-ordinate and perspective properties:

$(this).anima({ x: 200, z: 0, perspective: 1000 }, 800);

The API has other features, like delaying animations with delayAnima(ms), clearing the queue with clearAnima, and stopping the current animation with stopAnima. Any CSS property can be animated, along with shortcuts for scale[X|Y|Z], rotate, and skew.

loda-button

loda-button

loda-button (GitHub: lugolabs / loda-button) by Artan is a small plugin that animates the icon in a button while an asynchronous operation is performed. The recommended markup uses anchors and spans:

<a href="#" class="loda-btn">
  <span aria-hidden="true" class="loda-icon icon-mail"></span>
  Mail
</a>

And requires a bit of JavaScript to set it up:

var lodaBtn = $('#loda-btn').lodaButton();

The animation can be triggered by passing start to the button:

lodaBtn.lodaButton('start');

The icon fonts are IcoMoon by Keyamoon.

Echotube, Community Updates

01 Jul 2013 | By Alex Young | Comments | Tags media google community backbone.js

Echotube

Echotube

Echotube (GitHub: orizens / echoes, License: MIT) by Oren Farhi is a Backbone.js and RequireJS YouTube media manager. It’s open source, and the code is all JavaScript, so you can easily see how the author has structured the Backbone code around YouTube’s API.

The design is derived from Bootstrap, but there are a lot of custom widgets and CSS transitions which keep it feeling original. Also, Jasmine tests have been included, which is interesting because it seems like a slightly awkward thing to test.

If you’re looking for fully-fleshed out Backbone/RequireJS applications to learn from then give it a look.

Community Updates

I occasionally receive messages about major updates to libraries and products that I don’t always write about, but I thought it would be nice to start publishing those as well. If you read about BromBone – a service that provided access to headless browsers – then you might be interested to hear that BromBone is now a service for bringing better SEO to single page apps. It works by adding redirects to yoursite.brombone.com based on the crawler’s user agent. The documentation has a simple .htaccess file which will work for Apache.

Also of note is Vincent Voyer’s lazyload script has been updated to 2.0:

Feel free to contact us about your module/script/app’s major updates and I shall endeavour to find space to write about it.