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.

MV* and Local Storage

20 Jun 2013 | By Alex Young | Comments | Tags frameworks mv* localStorage

Most AngularJS and Backbone.js projects that I’ve worked on have persisted data to a remote API. What about those times when storing data in the browser is sufficient? Enterprising developers have added support for localStorage to some MVC frameworks, but before dropping one of these plugins or libraries into your project you need to know a little background about the API and its limitations.

Browser Support

If you’re already set on building a modern, single page web application, legacy browser support probably isn’t a huge deal. The Can I use Web Storage page shows most browsers we typically target are supported. It refers to “name/value pairs” because it’s talking about the localStorage API.

The localStorage API

If you’ve never used it before, then you can think of window.localStorage as a key/value store for strings. You can stick any JavaScript value you like in there, but a string will be returned on retrieval.

window.localStorage.setItem('age', 18);
window.localStorage.getItem('age');
// "18"

This means you should think carefully about what data you store. Aspirations of creating a browser-based Photoshop backed by localStorage isn’t architecturally sensible – it would be nice if binary data could be stored, but for now you’ll have to make do with strings.

The storage limit in most browsers is 5 MB, which probably doesn’t sound like much, but it’s actually 1000 times more than is supported by cookies.

AngularJS

There are examples of apps that use localStorage on the AngularJS blog. One that I downloaded and picked apart was FoodMe by Igor Minar. In FoodMe, Igor creates a localStorage service which basically just wraps window.localStorage so it can be loaded with dependency injection. The $scope is then watched, and a string version of a given record is dumped into localStorage using JSON.stringify:

foodMeApp.factory('customer', function($rootScope, localStorage) {
  var LOCAL_STORAGE_ID = 'fmCustomer';
  var customerString = localStorage[LOCAL_STORAGE_ID];

  var customer = customerString ? JSON.parse(customerString) : {
    name: undefined,
    address: undefined
  };

  $rootScope.$watch(function() { return customer; }, function() {
    localStorage[LOCAL_STORAGE_ID] = JSON.stringify(customer);
  }, true);

  return customer;
});

The record is loaded from localStorage, and serialised using JSON.parse and JSON.stringify. Notice that Igor has used the object-style API: localStorage.setItem(key, value) and localStorage[key] = value are equivalent.

Backbone.js

Jerome Gravel-Niquet created Backbone.localStorage (GitHub: jeromegn / Backbone.localStorage, License: MIT, bower: backbone.localStorage), which allows collections to store data with localStorage. It’s a drop-in solution – barely any configuration is required. All you need to do is add a localStorage property to your collection classes.

Backbone.localStorage has tests, and the author is still updating it. GitHub currently lists 31 contributors.

Knockout

This isn’t meant to be an exhaustive review of localStorage libraries, but I thought I’d also mention Knockout. knockout.localStorage (GitHub: jimrhoskins / knockout.localStorage) by Jim Hoskins makes ko.observable and ko.observableArray objects able to persist data to localStorage. You’ll need to specify a persist property which includes the key to store the observable’s data under.

It’s not quite as well-maintained or tested as Backbone.localStorage, but it does the job. There are some open pull requests that add things like AMD support.

Events

The Web Storage specification also defines a “storage” event. It fires when data changes, but you can’t stop it unlike other DOM events. This might make a more convenient bridge to data-binding frameworks.

Sync

If you’ve made an amazing single page app that persists data to localStorage, and you’re interested in adding a server-side API so users can save and sync data, what do you do? Well, step back and redefine the problem. Since localStorage is limited in size, why not use it like a caching layer? Your application could store data locally until a server is available, which suits a lot of use-cases, including mobile deployment. This is exactly what Backbone Caching Sync by Yiorgis Gozadinos does.

Cache

Another use people have found for localStorage is caching client-side assets. One example of this is basket.js by Addy Osmani.

Bing and Google Search make extensive use of localStorage for stashing SCRIPT blocks that are used on subsequent page views. None of the other top sites from my previous post use localStorage in this way. Are Bing and Google Search onto something? Yes, definitely.

Summary

If you need to persist data, localStorage can slot into data-binding and MVC/MVVC frameworks rather nicely. There are libraries out there, but with JSON.parse and JSON.stringify it’s trivial to store data. For applications with a server, then localStorage can be used as a temporary cache, which has the added benefit of helping support devices with intermittent network access.

Node Roundup: Node 0.10.12, grunt-micro, connect-prerenderer

19 Jun 2013 | By Alex Young | Comments | Tags node modules cluster grunt connect express
You can send in your Node projects for review through our contact form.

Node 0.10.12

Node 0.10.12 was released yesterday. This version updates v8 and npm, and has a fix for the net module.

One minor change that I liked was readline now supports CTRL-L for clearing the screen – that means Node’s command-line interface will do this as well. Before hitting CTRL-L did nothing, which wasn’t very intuitive if you’re used to using readline tools.

grunt-micro

If size is important to you, then you’ll like grunt-micro (GitHub: markdalgleish / grunt-micro, License: MIT, npm: grunt-micro) by Mark Dalgleish. This Grunt plugin ensures a script is smaller than a given size. Mark suggests this is useful for client-side authors that have size claims in their project documentation, but it could be useful for other things, like warning about asset sizes in mobile projects.

connect-prerenderer

connect-prerenderer (GitHub: dai-shi / connect-prerenderer, License: BSD, npm: connect-prerenderer) by Daishi Kato is middleware for pre-rendering content to support systems that don’t interact well with Ajax-heavy interfaces. This is ideal for improving the SEO of a site.

The author has paid special attention to AngularJS – the documentation includes some Angular client-side code that adds support for the module.

jQuery Roundup: Magnific Popup, blend.js

18 Jun 2013 | By Alex Young | Comments | Tags jquery plugins graphics images lightbox
Note: You can send your plugins and articles in for review through our contact form.

Magnific Popup

Magnific Popup

Magnific Popup (GitHub: dimsemenov / Magnific-Popup, License: MIT, jQuery: magnific-popup) by Dmitry Semenov is a responsive lightbox plugin that should work with mobile devices and also Zepto.js. It’s modular and has a build tool so you can generate a build that only includes the features you need. Sass is used for CSS, so you could easily customise the styles to suit your project.

Keyboard shortcuts are supported, the arrow keys and escape allow images to be navigated – see the gallery demo for an example of this.

A lot of the work is done by CSS, which means high DPI displays are supported:

Default controls are made with pure CSS, without external graphics. For the main image there is a built in way to provide appropriate source for different pixel density displays.

Content other than images is supported as well. The documentation has examples of using Magnific Popup with Google Maps and videos. For more information, see the Magnific documentation.

blend.js

blend.js (GitHub: qur2 / blend.js, License: MIT) by Aurélien Scoubeau applies effects to images using Canvas. The effects themselves are functions that receive pixels. Processing is applied to sections of the image in a two-dimensional grid.

Custom parameters can be passed to blending functions:

// Create some effects that will use additional arguments
var colorfx = blend.cfx(function(color, context) { return context; });
var anglefx = blend.pfx(function(angle, radius, pixels) { return pixels; });

blender.fx(colorfx, 'rgb(255, 123, 123)').fx(anglefx, [Math.PI, .25]);
blender.fx(colorfx, '#FFF', '#AAA', '#666', '#111');

// Null is used to skip zones
blender.fx(colorfx, '#FFF', null, null, '#111');

// Update the image
blender.update();

There are some bundled effects as well: desaturate, neutralize, vignette, and contrast. These can be found under blend.fx.

The author has included Mocha tests which can be ran in a browser here: blend.js/test.html.

Backbone Fetch Cache, Backbone.VirtualCollection, WTCSS

17 Jun 2013 | By Alex Young | Comments | Tags backbone.js plugins

Backbone Fetch Cache

Backbone Fetch Cache (GitHub: mrappleton / backbone-fetch-cache) by Andy Appleton caches Backbone’s collection and model fetch requests. Data is stored in localStorage to speed up rendering. This is useful for caching Ajax requests with APIs that don’t allow control over response cache headers.

The plugin supports preloading data with the prefill option which can be passed to fetch, and the author has included some Jasmine tests.

Backbone.VirtualCollection

Backbone.VirtualCollection (GitHub: p3drosola / Backbone.VirtualCollection, License: MIT, npm: backbone-virtual-collection) by Pedro Solá allows Backbone.Marionette’s CollectionViews and CompositeViews to be used with instances of Backbone.Collection. This allows collections to be projected and sorted.

This example is from the project’s documentation:

var virtual_collection = new Backbone.VirtualCollection(tasks_collection, function (task) {
  return task.get('user_id') == 13;
});

var view = new TaskListView({
  collection: virtual_collection
});

The project has Mocha tests and some details on its philosophy in the readme.

WTCSS

WTCSS

WTCSS (GitHub: benfoxall / wtcss, License: MIT) by Ben Foxall uses PhantomJS to analyse the CSS on a page, then attempts to visually indicate where each rule applies to using a Canvas overlay.

It looks impressive – there are demos on the project’s homepage, and I suspect it could form the basis for a more advanced CSS analysis and debugging tool.