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.

RobotsConf, DownDoc, opensemanticapi

28 Jun 2013 | By Alex Young | Comments | Tags robots events markdown google node

RobotsConf

RobotsConf

RobotsConf will take place on December 6th in Florida, and is a hardware-focused event aimed at developers who use high-level languages like JavaScript. Organised by Chris Williams (aka @voodootikigod), RobotsConf is a practical event to get you started in the Maker Movement:

If you are a Ruby, Python, JS or any other high level language developer that is interested in the Maker Movement, but unsure where to start – this event is designed for you. We will have experts in each high level language in attendance and available as well as many of the incredible makers who are already changing the world. With hands-on sessions covering drones, 3D Printing, microcontrollers, and the Internet of Things, this is the only two day event that will take you from a software developer to a Maker.

It’s organised by the JSConf team, so you know you’ll be in safe hands! Tickets start at $550 for early birds, and then $750 for a regular ticket.

DownDoc

If you followed my Backbone.js Google Tasks tutorials then you’ll know all about the wonders of gapi. DownDoc (GitHub: marksteve / downdoc, License: MIT) by Mark Steve Samson uses another Google API to store Markdown documents in Google Drive. If you’re tired of working with Word-like documents, then why not give it a try? It’s entirely browser-based, and the original source is pretty much a single CoffeeScript file.

opensemanticapi

opensemanticapi (GitHub: monbro / opensemanticapi, License: MIT) by Michael Klein is a “semantic wording database” made with Node and Redis. After leaving it running for a few hours it will have downloaded enough data to produce interesting results. Michael has some examples in the project’s readme, for example:

// http://localhost:8080/relations/ship

["midshipmen", "aboard", "ships", "rating", "master", "served", "seaman", "sea", "officers", "santa", "sailing", "cadets", "able", "sail", "navigation", "lieutenant", "hms", "expected", "yahoo", "storm", "rated", "promotion", "maría", "lewis", "false", "era", "boys", "wind", "voyage", "volunteer", "servants", "required", "passing", "palos"]

One thing that interests me about this is as a brainstorming tool for authors, as an alternative to a thesaurus.

Build Your Own Twitter-Clone with Sproute

27 Jun 2013 | By Louis Stowasser | Comments | Tags tutorials mongodb
Louis Stowasser is the creator of Crafty, and has worked at Mozilla. This tutorial is about Sproute, a commercial web framework that's similar to Meteor. DailyJS readers can download Sproute for free with the discount code dailyjs.

Sproute

Application development on the web is not easy. You need to understand server-side languages, databases, performance, security… the list goes on. It can take months to develop even simple applications. Sproute is a new kind of web framework that allows you to create apps in minutes.

In this tutorial we will be creating a mini-Twitter clone complete with a feed, login/register and profile page. It shall be called “Critter”.

Sproute is currently available on a commercial license to fund further development. Use the discount code dailyjs to get it free or contact us at contact@sproute.io.

The structure of a Sproute app is as follows:

  • Views: HTML pages with embedded template tags to request and display data.
  • Models: JSON object to define what the data looks like.
  • Controller: A mapping from URLs to Views using routes.

Setup

After installation you will need to edit config.json. Add a name property:

{
  "name": "critter"
}

This will create a Mongo database called critter.

The Feed

This will be a view that lists the micro-blog posts by a user. Create a view under the views/ directory called feed.sprt. .sprt is the default extension for views, you may change this in the config.json file.

To get the data from the Mongo database, we need to use the template language; in particular the tag get. All data is read, updated, created and deleted through an HTTP interface prefixed with /data/ so we must construct a URL to get the post data.

This will retrieve every row in the posts collection. Generally we want a feed of a particular user so we need to filter the results by username.

A few things to explain here. First of all the two parts to the URL will filter the results where the field name equals the value.

Secondly _creatorName is an in-built field so whenever a row is created, Sproute will automatically add some metadata about the row; in this case the username who created the post.

Lastly, params.user is a placeholder from a route in the controller that points to this view.

{
  "/:user": "feed"
}

This route means anything requested after / will render the view feed.sprt and put the value in the params object under the key user. Let’s use an example:

GET http://example.com/louisstow
params.user == "louisstow"

So now that we have all the post data under a given user, we need to render it by looping over each post. We do this with the template tag each and some HTML.

Before we run this, we’re missing one little piece. We’re requesting data from a collection called posts which doesn’t currently exist. We need to define it as a model to ensure some data integrity.

Models are defined as JSON files under the models/ directory. Create a file called posts.json. Sproute will create a collection for each model using the filename. Inside the model, we should define the field we will be using.

{
  "content": {"type": "String"}
}

Yep, that’s it. The model tells Sproute that the posts collection has a content field of type string (text). Everything else we use is an in-built field. You can add some more constraints in here such as minimum and maximum length. Maybe we could limit it to 140 characters ;).

Posting a Micro-Blog

Now that we can display the data, let’s make sure we can create it via some HTML in feed.sprt:

Plain old HTML is enough to insert data in Sproute by setting the action to the HTTP interface and the method to post.

Notice the query variable goto. It’s a nice feature that will redirect the user after doing the action, you will see it used in a few other end-points throughout the project. We also use self.url to get the current page to redirect to.

User Accounts

Sproute has user accounts built in. You just have to create the front-end including the login and register page. Create two views, login.sprt and register.sprt.

Send a POST request to /api/login with the username and password to create a session and log that user in.

Send a POST request to /api/register with the desired username, password and any other values you want stored with the user to create a new user row. This does not log them in.

Logging the user out is as simple as visiting /api/logout.

We can restrict HTML from rendering in our views if the user is not logged in. The form to post a micro-blog should only appear for users who are logged in:

The Home Page

Our controller doesn’t handle the index or home page. Add another route before the feed and create a view called home.sprt.

{
  "/": "home",
  "/:user": "feed"
}

What to put on the home page? This is up to you, maybe a bit of a splash page to introduce the reader to your new micro-blog. Maybe we want to show off some of the users.

Secure It

After creating a fully functioning micro-blog, the next step is to lock it down. Right now anyone can create a post whether or not they are logged in. There is a nice feature in Sproute where you can specify a route (just like the controller) and who can access it. It’s defined in permissions.json.

Let’s evaluate our product and decide what we need to secure. We don’t want just anybody creating a post, we want them at least to be members, so let’s add that restriction:

{
  "POST /data/posts": "member"
}

member is a default user type. You can create your own user types by overriding the in-built users model. There are also special user types:

  • owner: Give access to the logged in user where the _creator field matches their user ID.
  • stranger: Give access to a user who is not logged in.
  • anyone: No restriction.

For anyone to create a post, they must be logged in. We also need to make sure not just anybody can delete or edit the posts.

{
  "POST /data/posts": "member",
  "DELETE /data/posts": "admin",
  "DELETE /data/posts/*": "owner",
  "POST /data/posts/*": "owner"
}

An entire collection can be wiped by sending a DELETE request to /data/<collection> so add a restriction that only admin accounts can do that.

Let the creators be able to remove their own posts through DELETE /data/posts/*. Similarly let them edit their own posts.

Conclusion

The end! Hopefully this tutorial has taught you a few things about using the Sproute framework and how simple it is to build dynamic websites. Visit http://sproute.io to see all the other web applications you can build in minutes.

Node Roundup: CampJS, bower-registry, Helmsman

26 Jun 2013 | By Alex Young | Comments | Tags node modules events command-line bower
You can send in your Node projects for review through our contact form.

CampJS

CampJS August

CampJS will be held in the Gold Coast, Australia, on August 9th to 12th. TJ Holowaychuk will be attending, and also Angelina Fabbro.

If you’re interested, tickets start at AU$320. DailyJS readers can get a $25 discount by using the code DAILYJS.

bower-registry

If you’re looking to set up your own Bower registry, then take a look at bower-registry (GitHub: neoziro / bower-registry, License: MIT, npm: bower-registry) by Greg Bergé. This is an Express web application that stores data in Redis, but the author notes it could be easily adapted to support other databases like MongoDB and PostgreSQL.

Running bower-registry -d redis on the command-line will start a server. Other options can be viewed by typing bower-registry -h. The app can also be loaded as a Node module, and require('bower-registry').Registry is the Express app instance.

Helmsman

Helmsman (GitHub: mattmcmanus / node-helmsman, License: MIT, npm: helmsman) by Matt McManus is an opinionated command-line application development kit. The interface style is based on Git’s subcommands:

A common setup for command line applications is <command> <subcommand> <arguments/options> (for example: git commit -m 'message'). Rather than having a giant file that switches or if elses over each potential subcommand, it’s much neater to store each subcommand in it’s own file (bin/command,bin/command-subcomand, bin/command-subcommand2, etc). Doing this however introduces some annoying manual steps which helmsman hopes to solve.

The subcommand-style API is based on metadata exposed through exports. If the file is run directly rather than loaded with require, then your script should run as it would normally:

#!/usr/bin/env node

// 1. To expose the metadata simply `exports.command`
exports.command = {
  description: 'Show current worker counts and their pids'
};

// 2. Then make sure it only runs when it's directly called:
if (require.main === module) {
  // Parse options and run the magic
}

jQuery Roundup: Backbone Associations, bootstrap-wysihtml5

25 Jun 2013 | By Alex Young | Comments | Tags jquery plugins bootstrap backbone.js text wysiwyg
Note: You can send your plugins and articles in for review through our contact form.

Backbone Associations

Backbone Associations (GitHub: dhruvaray / backbone-associations, License: MIT, bower: backbone-associations) by Dhruva Ray is a plugin for one-to-one and one-to-many associations between models and collections:

applications can listen to any kind of change (change, add, remove, reset, sort, destroy) in this hierarchy using standard Backbone events and respond to them. (views can re-render for example). The implementation strives to be tiny (2.2KB), easy-to-understand, light-weight and fast.

Once the plugin has been loaded, models can be defined using Backbone.AssociatedModel, and then relationships can be set up with Backbone.One and Backbone.Many.

var Product = Backbone.AssociatedModel.extend({
});

var User = Backbone.AssociatedModel.extend({
  relations: [{
    type: Backbone.Many,
    key: 'locations',
    relatedModel: Product
  }]
});

The reversed association is automatically inferred, so a product could be set for a user. Values can be traversed using fully qualified paths as well:

emp.get('works_for.controls[0].locations[0].zip');

Fully qualified paths can also be used to assign event listeners:

emp.on('change:works_for.locations[*]', cb);

The author has written up a full tutorial for Backbone Associations, and has included unit tests and full documentation.

bootstrap-wysihtml5

bootstrap-wysihtml5 (GitHub: jhollingworth / bootstrap-wysihtml5/, License: MIT, bower: bootstrap-wysihtml5) by James Hollingworth is an amazing text editor component. It’s highlight consistent with Bootstrap’s design, and has many features you may take for granted when editing text, like the usual keyboard shortcuts.

Trantor Liu sent in his fork, trantorLiu/bootstrap-editor, which pairs up the project with jQuery-File-Upload. This adds support for things like upload progress, drag and drop, and cross-domain uploads. Trantor notes that the demo won’t currently work because there’s no server-side support, but he’s provided instructions on how to set it up locally.

JS-Git Update, X-editable

24 Jun 2013 | By Alex Young | Comments | Tags bootstrap ui widgets git

JS-Git

JS-Git logo

Tim Caswell’s JS-Git project has gone through the proof-of-concept stage, and he’s now reached an impasse where he’s looking for more funding. There’s a JS-Git repository that has specifications for the core parts of the project. This includes interfaces for how backends can be written, including details on using HTML5 APIs or a real file system with Node.

The Git Database specification defines how objects and refs should be stored, based on ECMAScript syntax. The beginnings of a reference implementation can be found in fs-db.js, which uses Node’s fs module.

The new fundraising campaign, run on BountySource, aims to raise $30,000 to enable Tim to work on the project full time to move the project closer to his main goals. This includes cloning remote repositories to local storage over http, git, or ssh, making and committing local changes offline, and pushing changes back to remote repositories. The target platforms are ChromeOS, Firefox OS, Windows RT WinJS, and HTML5 web apps.

It’s an ambitious project, but Tim admits in the BountySource posting that he won’t reach 100% completion. The effort reminds me of a JavaScript-centric version of libgit2, and has particular relevance for anyone interested in bringing native development tools to new web-based platforms like ChromeOS.

X-editable

X-editable

X-editable (GitHub: vitalets / x-editable, License: MIT, bower: x-editable) by Vitaliy Potapov is an in-place editing library that works with Bootstrap, jQuery UI, and jQuery. It can display a popup for a simple text field, or richer input widgets like date selectors.

I like to use it with data attributes, so I have simple markup that drives the keys and values for various UI elements, and then a generic RESTful API that the data is persisted to. I’ve been using it for Bootstrap CMS-style interfaces, with a Grunt/bower build environment, and it’s been solid so far. The author has included tests and documentation.

Backbone and Azure, Yass.js, grunt-stripmq

21 Jun 2013 | By Alex Young | Comments | Tags backbone.js mobile css grunt

Backbone Adapter for Azure

Olivier Bloch sent in a Backbone adapter for Windows Azure (GitHub: MSOpenTech / backbone-azure-mobile-services, License: Apache 2.0). It’s distributed by Microsoft Open Technologies, and syncs data with the Windows Azure Mobile Data Service.

If you’re interested in trying out the server-side API without Backbone.js, I noticed there’s a tutorial here: Get started with data in Mobile Services.

To use Azure with Backbone, all you need to do is include the adapter, an additional JavaScript file provided by Microsoft, and some settings for your collections:

var People = Backbone.Collection.extend({
  client: client,
  table: 'Table1',
  model: Person
});

The authors have included build scripts (Grunt) and tests (Jasmine).

Yass.js

Yass.js (GitHub: EightMedia / yass.js, License: MIT) by Jorik Tangelder is an adaptive image script that adds support for srcset tailored to mobile browsers. Once yass.js has been added after the last image on a page, it will ensure the optimum image is loaded.

It’s currently very small (less than 500 bytes when compressed), and has been tested in Chrome 28, Android 4.2, IOS6, BlackBerry10 and IE6.

grunt-stripmq

grunt-stripmq (GitHub: jtangelder / grunt-stripmq, License: MIT, npm: grunt-stripmq) also by Jorik Tangelder is a “mobile-first CSS fallback”:

A Grunt task to generate a fallback version of your fancy mobile first stylesheet. Since IE9 doesn’t support media queries, you can use a JavaScript like respond.js to enable this, or generate a fallback version with this task.

So if you’ve invested a lot of time developing modern, mobile-optimised sites, then you should be able to jam them through Grunt to spit out something desktop-friendly.