Backbone.js Tutorial: Creating Lists

03 Jan 2013 | By Alex Young | Comments | Tags backbone.js mvc node backgoog

Preparation

Before starting this tutorial, you’ll need the following:

  • alexyoung / dailyjs-backbone-tutorial at commit 82fe08e
  • The API key from part 2
  • The “Client ID” key from part 2
  • Update app/js/config.js with your keys (if you’ve checked out my source)

To check out the source, run the following commands (or use a suitable Git GUI tool):

git clone git@github.com:alexyoung/dailyjs-backbone-tutorial.git
cd dailyjs-backbone-tutorial
git reset --hard 82fe08e

List CRUD

The last few parts of this tutorial series have demonstrated how to talk to Google’s Tasks API and authenticate with OAuth. At this point, you should be able to sign in and see a list of task lists.

As we’ve seen, Backbone.js is based around RESTful APIs that speak in terms of CRUD (create, read, update and delete). In Part 4, I explained how to write a custom Backbone.sync method that can communicate with Google’s APIs, but so far we’ve only implemented “read” functionality, which fetches task lists using gapi.client.tasks.

Now we really need to implement the full set of CRUD operations so users can manage lists. Part 4 showed how Google’s API maps to Backbone’s sync operations:

Google Tasks APIBackbone.sync MethodDescription
insertcreateCreate a new task.
updateupdateUpdate an existing task.
deletedeleteDelete a task.
listreadGet a list of tasks.

In this part we’ll add support for “create”, but as you’ll see the principles are very similar to the “read” implementation.

Creating Lists

In order to create lists, several new components are required:

  1. Suitable buttons
  2. A form template
  3. Add and edit views
  4. Controller code

In Backbone.js, models and collections emit events. We’ve already created code to manage list item views, so all we need to do is hook this up to the event that fires when a new model is created and added to the TaskLists collection.

Mastering and exploiting events in this way is one of the tricks to writing manageable Backbone.js code.

Backbone.sync

So far, Backbone.sync can only read lists from Google’s API. To make it capable of creating items we’ll need a little bit of extra code. This will build upon what we’ve already written, so it’ll be short and sweet.

Go back to app/js/gapi.js and change Backbone.sync to call gapiRequest when the create operation is invoked:

Backbone.sync = function(method, model, options) {
  var requestContent = {};
  options || (options = {});

  switch (method) {
    case 'create':
      requestContent['resource'] = model.toJSON();
      request = gapi.client.tasks[model.url].insert(requestContent);
      Backbone.gapiRequest(request, method, model, options);
    break;

This looks a lot like the “read” code. There is one more thing we need to do in this file – change Backbone.gapiRequest to deal with single resources. I’ve put the full code for the method below because it’s still short with the modifications for this tutorial:

Backbone.gapiRequest = function(request, method, model, options) {
  var result;
  request.execute(function(res) {
    if (res.error) {
      if (options.error) options.error(res);
    } else if (options.success) {
      if (res.items) {
        result = res.items;
      } else {
        result = res;
      }
      options.success(result, true, request);
    }
  });
};

This looks to see if an array of items has been returned by Google’s API, or simply a single object. There’s an important lesson here though: Backbone.sync is sandwiched between other Backbone code, and is capable of providing Backbone with properties that will be used to set model attributes later on. This code doesn’t look like it does much, but the success callback will receive result, which will have an id property when models are created. Backbone will see this id property and use it to set the model’s id attribute, automatically!

Many Bothans died to bring us this information.

Template Junk

Open app/js/templates/app.html and update the signed-in-container div to contain a list and another container div:

<ul class="nav nav-tabs" id="top-nav">
  <li class="buttons">
    <div class="btn-group">
      <a href="#" class="btn" id="add-list-button"><i class="icon-plus">Add List</i></a>
      <a href="#" class="btn" id="edit-list-button"><i class="icon-cog">Edit List</i></a>
      <a href="#" class="btn delete-list" id="delete-list-button"><i class="icon-trash">Delete List</i></a>
    </div>
  </li>
</ul>
<div id="content-container">
  <div id="list-editor"></div>
  <div id="tasks-container"></div>
</div>

This has the “Add List” button that you’ll be able to use by the end of this tutorial, and it also has a div that’ll contain the list add/edit form.

Now open app/js/templates/lists/form.html and paste this in:

<fieldset>
  <legend>
    <span class="form-title">Edit List</span>
    <a href="#" class="pull-right delete-list btn"><i class="icon-trash"></i></a>
  </legend>
  <div class="control-group">
    <label class="control-label" for="list_title">Title</label>
    <div class="controls">
      <input type="text" class="input-xlarge" name="title" id="list_title" value="" placeholder="The list's title">
    </div>
  </div>
</fieldset>
<div class="form-actions">
  <button type="submit" class="btn btn-primary">Save Changes</button>
  <button class="cancel btn">Close</button>
</div>

This is the body of a form that will be used to add or edit lists. It uses the variable interpolation features we’ve already seen in this tutorial series.

Add and Edit Views

I’m only going to cover adding lists in this tutorial, we’ll get to the other functionality later (mainly because I’ve been writing this for three hours and I have client work to do and I need to pay the bills). Bill-paying aside, what’s the difference between an “add” and “edit” view? The form.html template can be reused by both, so why don’t we create an edit view and just inherit from it to make the list add view?

Open app/js/views/lists/edit.js and add this new view:

define(['text!templates/lists/form.html'], function(template) {
  var EditListView = Backbone.View.extend({
    tagName: 'form',
    className: 'form-horizontal well edit-list',
    template: _.template(template),

    events: {
      'submit': 'submit'
    , 'click .cancel': 'cancel'
    },

    initialize: function() {
      this.model.on('change', this.render, this);
    },

    render: function() {
      var $el = $(this.el);
      $el.html(this.template(this.model.toJSON()));

      if (!this.model.get('id')) {
        this.$el.find('legend').html('Add List');
      }

      return this;
    },

    submit: function() {
      var self = this
        , title = this.$el.find('input[name="title"]').val()
        ;

      this.model.save({ title: title }, {
        success: function() {
          self.remove();
        }
      });

      return false;
    },

    cancel: function() {
      this.$el.hide();
      return false;
    }
  });

  return EditListView;
});

In this class, I’ve declared events for submitting and closing the form, and bound them to suitable methods. I’ve also bound the change event on the view’s model to render, so changes to the model will automatically get displayed. This will be important later on.

Notice that in render, the legend will be changed when the model doesn’t yet have an id. In other words, when the model is new and hasn’t been saved, show a different title and hide the delete button.

Now compare this file to app/js/views/lists/add.js:

define([
'models/tasklist'
, 'views/lists/edit'
],

function(TaskList, EditListView) {
var AddListView = EditListView.extend({
  submit: function() {
    var self = this
      , title = this.$el.find('input[name="title"]').val()
      ;

    this.model.save({ title: title }, { success: function(model) {
      // Add the updated model to the collection
      bTask.collections.lists.add(model);
      self.remove();
    }});

    return false;
  }
});

return AddListView;
});

This file uses RequireJS to load EditListView, and then inherits from it. The submit method is replaced because creating lists is slightly different to updating them. When lists are created, it’ll receive an updated model from the server in the success callback, which can be added to the global lists collection. The view removes itself afterwards.

Add List Button

A link for adding lists was added to the main app.html template earlier on. To hook it up, open app/js/views/app.js and add a new method called addList:

addList: function() {
  var list = new bTask.collections.lists.model({ title: '' })
    , form = new AddListView({ model: list })
    , self = this
    ;

  this.$el.find('#list-editor').html(form.render().el);
  form.$el.find('input:first').focus();

  return false;
}

This will render the AddListView template and focus on the title field. You’ll also have to change the top of the file to load AddListView:

define([
  'text!templates/app.html'
, 'views/lists/add'
],

function(template, AddListView) {

Finally, add the events bindings somewhere in AppView:

events: {
  'click #add-list-button': 'addList'
},

Summary

Adding Lists

If you run node server and visit http://localhost:8080, you should now be able to add lists. The project doesn’t look particularly cool yet, but I’ll get to that soon.

The full source for this tutorial can be found in alexyoung / dailyjs-backbone-tutorial, commit 465523f.

Node Roundup: 0.9.5, juxt, email-templates

02 Jan 2013 | By Alex Young | Comments | Tags node modules email express functional
You can send in your Node projects for review through our contact form or @dailyjs.

Node 0.9.5

Node 0.9.5 (unstable) is out, and Isaac said weekly releases will be the norm for the near future:

For the next month at least, the primary focus will be on bug fixing and performance. Expect nearly-weekly releases until v0.10 is ready.

Amongst the raft of bug fixes, the updated stream module has some tweaks as well:

  • stream: fix to emit end event on http.ClientResponse (Shigeki Ohtsu)
  • stream: fix event handler leak in readstream pipe and unpipe (Andreas Madsen)

juxt

juxt (License: WTFPL, npm: juxt) by Azer Koculu is a small module that takes in functions and outputs a new function that stitches them together:

function inc1(n) { return n+1 };
function inc2(n) { return n+2 };
function inc3(n) { return n+3 };

juxt(inc1, inc2, inc3)(314); // returns [315, 316, 317]

It also has an asynchronous API, and will intelligently collate arguments into arrays or objects.

email-templates

email-templates (License: MIT, npm: email-templates) by Nick Baugh is a module for rendering email templates using ejs and “email-friendly” inline CSS. When I make Node web applications, I usually treat emails as an afterthought, rendering them with Jade or ejs. However, there are times when more attention to design is required, and this is made difficult in email due to the way certain major email clients treat CSS.

Juice from LearnBoost is used to generate suitable style attributes based on your CSS, making the task of inlining CSS less messy. The module will also generate a text version of the email if a suitable template is provided. The author has provided a full example with Nodemailer.

Nick also sent in a few of his other interesting modules, including express-cdn (GitHub: niftylettuce / express-cdn, License: MIT, npm: express-cdn) which automatically optimises assets in Express applications. The assets will be delivered using Amazon S3 and CloudFront, so you can create your own CDN.

jQuery Roundup: jKit, ZinoUI, jQuery.ajax.fake

01 Jan 2013 | By Alex Young | Comments | Tags jquery plugins frameworks ui ajax testing
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

jKit

jKit's site includes demos of every effect and component.

jKit (GitHub: FrediBach / jQuery-jKit, License: MIT) by Fredi Bach is a relatively small (47 KB) UI toolkit. It can work with data attributes, so adding data-jkit attributes to the relevant elements will invoke various components.

There are a lot of effects and components, including tooltips, charts, parallax scrolling, and a lightbox. The project has detailed documentation on each of the bundled plugins, and a simple introduction for non-programmers.

ZinoUI

The ZinoUI TreeView component.

Coincidentally, Dimitar Ivanov also sent in a UI toolkit of sorts: the ZinoUI Framework (License: CC BY-NC 3.0). This framework requires commercial licensing starting at $50 per site, and includes advanced widgets more comparable to jQuery UI, like a calendar and tree view.

ZinoUI is WAI-ARIA compatible, so may suit projects with stricter accessibility requirements. It has been tested with Google Chrome 12+, Firefox 4+, Safari 5+, Opera 11+, and IE8+.

jQuery.ajax.fake

jQuery.ajax.fake (GitHub: anasnakawa / jquery.ajax.fake, License: MIT, component: anasnakawa/jquery.ajax.fake) by Anas Nakawa can be used to mock jQuery $.ajax calls. A mocked call will be made when passing fake: true as an option to $.ajax. It can be disabled globally, and works with deferred calls.

JS101: A Primer on Strings and String Encodings

31 Dec 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner

What is a JavaScript string? It depends on the context. For instance, a string is a primitive value – a value represented at the “lowest level” of the language’s implementation.

Strings are also members of the type String. Strings can be created with the String constructor. Running new String('hello') creates an instance of String.

Finally, String literals are found in the program’s source: var name = 'alex'.

Given that there are many ways to represent strings, what is the underlying encoding in JavaScript? Both the third and fifth editions of ECMAScript state that strings are represented as 16-bit unsigned integers:

Each integer value in the sequence usually represents a single 16-bit unit of UTF-16 text. However, ECMAScript does not place any restrictions or requirements on the values except that they must be 16-bit unsigned integers.

String Encoding

Ultimately a string is just a sequence of characters. In other words, an array of units of information that correspond to digits, letters, and so on. Characters are represented as byte sequences.

When working on client-side JavaScript and HTML, we’re used to seeing charset=UTF-8. UTF-8 is a system for encoding characters, and is actually “variable width”, which means the bytes used to represent an individual character can vary in length.

I said earlier that JavaScript strings are 16-bit, so how does this relate to UTF-8? In extremely simplified terms for the purposes of a beginner’s article, you can think about it like this: JavaScript engines use a fixed 16-bit representation of characters that makes it easier to manage strings internally.

So, even though a browser’s JavaScript engine internally represents characters as 16-bit numbers, we don’t usually need to know about this. Writing the strings to form controls with the DOM or using XMLHTTPRequest should convert the string to the right encoding. Ideally the server should have sent the Content-Type header set to UTF-8, so the browser will know what to do.

More About Encodings

Even if you’re a client-side developer that doesn’t care about string encodings, Joel Spolsky’s The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets is worth reading because it explains the history behind string encodings. Understanding the history behind what can be a frustrating topic makes it easier to understand.

If you need to work on string encodings in JavaScript, Johan Sundström’s post Encoding / decoding UTF8 in javascript from back in 2006 explains how to encode and decode UTF-8.

Monsur Hossain went on to write UTF-8 in JavaScript which goes into unescape and encodeURIComponent in more detail.

CampJS, euh.js, node-startup

28 Dec 2012 | By Alex Young | Comments | Tags conferences events node

CampJS

CampJS

CampJS is a weekend-long JavaScript “hack retreat” taking place in Gold Coast Hinterland, Queensland, Australia, from February 15th to the 18th. Early bird tickets are $270, and then prices go up to $470 by the 1st of February.

Some well-known developers will be there, including Dominic Tarr and James Halliday (substack).

The event is organised by Tim Oxley, Nigel Rausch, and Geoffrey Donaldson. For more about the event, follow @campjsnews.

euh.js

euh.js (License: MIT, npm: euh.js) by Cristian Tincu is a console implementation that supports the usual log, warn, and error methods.

It’s exposed as the ø object, and has a chainable API. It can be installed with npm and ender (ender build euh.js).

node-startup

node-startup (License: MIT) by Anthony Ettinger is an init script for managing Node applications. The script itself, init.d/node-app, implements the usual start, stop, and restart commands, and will manage processes using PID files.

It’s exactly the kind of thing you can’t find when you need it, so it’s probably worth starring on GitHub if you’re the kind of developer that doesn’t typically have to deal with sysadmin tasks. I wrote about using Upstart for managing Node apps last year on DailyJS.

Backbone.js Tutorial: List Views

27 Dec 2012 | By Alex Young | Comments | Tags backbone.js mvc node backgoog

Preparation

Before starting this tutorial, you’ll need the following:

  • alexyoung / dailyjs-backbone-tutorial at commit fcd653ec6
  • The API key from part 2
  • The “Client ID” key from part 2
  • Update app/js/config.js with your keys (if you’ve checked out my source)

To check out the source, run the following commands (or use a suitable Git GUI tool):

git clone git@github.com:alexyoung/dailyjs-backbone-tutorial.git
cd dailyjs-backbone-tutorial
git reset --hard fcd653ec6

Wireframe

The application we’re building has several main interface elements:

  • A two column layout for displaying task lists and tasks
  • Forms for adding and editing each item type
  • Buttons for invoking the forms, deleting items, and clearing complete items
  • Task state control (done checkbox)

The image below shows the basic layout.

The application's wireframe.

In this tutorial we’ll start implementing the interface by using an unordered list to represent task lists.

List Items

Despite being relatively simple, implementing a navigable list of task lists involves several Backbone.js elements:

  • HTML templates
  • Backbone views: ListMenuView, ListMenuItemView
  • Backbone collection: TaskLists

The ListMenuView contains the task list menu, and the ListMenuItemView is the navigation item for each task list itself. This can be modeled as a ul and a set of li elements.

Create a new directory called app/js/views/lists to store the task list-related Backbone.View classes, and another called app/js/templates/lists for the corresponding templates.

View: ListMenuView

This view resides in app/js/views/lists/menu.js:

define(['views/lists/menuitem'], function(ListMenuItemView) {
  var ListMenuView = Backbone.View.extend({
    el: '.left-nav',
    tagName: 'ul',
    className: 'nav nav-list lists-nav',

    events: {
    },

    initialize: function() {
      this.collection.on('add', this.render, this);
    },

    render: function() {
      // TODO
    }
  });

  return ListMenuView;
});

It loads views/lists/menuitem which we’ll create in a moment. Then it binds itself to the .left-nav element which was created by AppView and its corresponding template. The menu itself is an unordered list, and it uses some class names that will become more relevant once styles are added.

Notice that this view expects a collection. Collections can be passed to views during instantiation. For example, new ListMenuView({ collection: lists }) will pass the lists collection to an instance of this view.

The render method should look like this:

render: function() {
  var $el = $(this.el)
    , self = this;

  this.collection.each(function(list) {
    var item, sidebarItem;
    item = new ListMenuItemView({ model: list });
    $el.append(item.render().el);
  });

  return this;
}

The view’s element is used as the container for each ListMenuItemView which is passed a model by iterating over the collection.

View: ListMenuItemView

The app/js/views/lists/menuitem.js is similar to the previous view, but makes use of a template and Backbone’s declarative event binding feature.

define(['text!templates/lists/menuitem.html'], function(template) {
  var ListMenuItemView = Backbone.View.extend({
    tagName: 'li',
    className: 'list-menu-item',

    template: _.template(template),

    events: {
      'click': 'open'
    },

    initialize: function() {
      this.model.on('change', this.render, this);
      this.model.on('destroy', this.remove, this);
    },

    render: function() {
      var $el = $(this.el);
      $el.data('listId', this.model.get('id'));
      $el.html(this.template(this.model.toJSON()));
      return this;
    },

    open: function() {
      var self = this;
      return false;
    }
  });

  return ListMenuItemView;
});

The template is app/js/templates/lists/menuitem.html:

<a href="#" class="list-title" data-list-id=""></a>

Notice that curly braces are used to insert values. This is provided by Underscore’s built-in template system.

The view’s open method is bound to click events, and I’ve also bound change and destroy model events to the view as well – these will come in handy later.

The template’s values are inserted by using the template method in render:

$el.html(this.template(this.model.toJSON()));

The model’s raw JSON is passed to template so title and id will be resolved to the correct values.

Invoking ListMenuView

Open app/js/app.js and add ListMenuView to the list of define requirements:

define([
  'gapi'
, 'views/app'
, 'views/auth'
, 'views/lists/menu'
, 'collections/tasklists'
],

function(ApiManager, AppView, AuthView, ListMenuView, TaskLists) {

Last week I added a console.log to print out the name of each list. Remove that code and change it to render the ListMenuView:

connectGapi: function() {
  var self = this;
  this.apiManager = new ApiManager(this);
  this.apiManager.on('ready', function() {
    self.collections.lists.fetch({ data: { userId: '@me' }, success: function(res) {
      self.views.listMenu.render();
    }});
  });
}

Go back up to the App constructor function to make it instantiate listMenu by passing the relevant collection:

var App = function() {
  this.views.app = new AppView();
  this.views.app.render();
  this.views.auth = new AuthView(this);
  this.views.auth.render();
  this.collections.lists = new TaskLists();
  this.views.listMenu = new ListMenuView({ collection: this.collections.lists });

  this.connectGapi();
};

Running It

Now if you run node server and visit http://localhost:8080/, you should see your task lists displayed in a simple unordered list.

Summary

The app is now communicating with Google, allowing users to sign in, and also displays the user’s task lists. It still doesn’t look too exciting because we haven’t yet applied any styles, but you should be able to adapt the code you’ve seen so far to work with other Google APIs and similar services.

This tutorial’s code is available in commit 82fe08e on GitHub.

Node Roundup: 0.9.4, screener, Jyql

26 Dec 2012 | By Alex Young | Comments | Tags node modules
You can send in your Node projects for review through our contact form or @dailyjs.

Node 0.9.4

Node 0.9.4 has been released, and this version is a milestone because it features the new streams API. There are the usual platform-specific bug fixes and other improvements to core modules.

The new streams API documentation was published as part of this release.

node-screener

node-screener (License: BSD, npm: screener) by Damian Kaczmarek is a module for validating objects, and the author notes it works with Mongoose:

var screen = require('screener').screen;
var object = {
  _id: "503cb6d92c32a8cd06006c53",
  user: { name: "Joe Doe", birthdate: "04.07.1980"},
  location: { lat: 16.5015636, lon: 52.1971881 }
};

var result = screen(object, {
  user: {
    name: 'string', // same effect would be if passed /.*/ regexp
    birthdate: /\d\d\.\d\d\.\d\d\d\d/
  }
  location: {lat: 'number', lon: 'number'}
});

Jyql

Jyql (License: MIT, npm: jyql) by Gianfranco Cecconi is a Node module and browser library for working with the Yahoo! Query Language engine. The Node module uses the request module by Mikeal Rogers to automatically fetch a suitable resource to be processed with YQL.

jQuery Roundup: jquery.columns, stackable.js

25 Dec 2012 | By Alex Young | Comments | Tags jquery plugins columns responsive tables
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

jquery.columns

jquery.columns (License: MIT) by Cedric Ruiz extends the $.css method to support viewport-percentage lengths, basically making it a lot easier to work with responsive grids.

The plugin provides a $.columns method, but passing sizes with vw units to $.css will work as well.

There’s a demo here: jquery.columns demo.

stacktable.js

stacktable.js (GitHub: johnpolacek / stacktable.js, License: MIT/GPL) by John Polacek is a plugin for stacking tables on small screens. It’s designed to work in responsive layouts by using media queries.

To make tables fit smaller screens, this plugin stacks each column vertically in order. The headers will be placed in the correct order as well. Behind the scenes, tables are actually replaced with the stacked version – by passing a specific class name to the plugin responsive layouts can be supported.

JavaScript Developer Survey 2012: Results

24 Dec 2012 | By Alex Young | Comments | Tags community surveys

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

Meteor seems to be struggling to gain traction.

98% of readers write client-side JavaScript, which is unchanged from last year. I included Meteor because it’s had so much press this year, but it seems like it’s still not very popular, at 2%.

I’ve always felt like this survey could be useful to those who are looking to create open source projects and even commercial services aimed at the JavaScript community. With that in mind, it’s interesting that 57% of respondents said they don’t currently write Node but are interested in learning about it. Only 9% were not interested. There are solid educational resources for Node out there, but it seems like people are hungry for more.

71% of respondents don’t use a language that compiles to JavaScript. This surprised me, because this year it certainly felt like more of our project submissions (for both client-side and server-side) were written in CoffeeScript.

Speaking of CoffeeScript, it was the most popular compile-to-JavaScript language, at 82%. TypeScript was second, at 14%, which is ahead of Dart by 10%.

There are plenty of worn out semicolon keys out there.

I thought the question “What JavaScript stylistic choices do you prefer?” may have resulted in controversy, but thankfully we got some interesting results. At 85%, most respondents use semicolons. And, 67% use commas at the end. 53% use spaces, with 39% tabbing instead. I would have thought spaces were more popular, but I’ve seen a lot of open source client-side projects that use tabs, so the JavaScript community isn’t as settled on tabs vs. spaces as some other popular languages.

My philosophy on this is to always match the style of the project you’re working on, and you’ll see me doing this in some planned DailyJS eBooks for 2013.

Testing and Benchmarking

51% of respondents don’t write tests – down from 58% last year.

Jasmine is the most popular testing library, at 45%, with Mocha close behind at 41%. QUnit is also very popular with 31%. For reference, these were last year’s test library results:

Jasmine (44%) has edged out QUnit (41%)! Vows is also doing well with 13%. Express/Mocha scored 11%, slightly ahead of Nodeunit at 8%.

Vows is now down to 7%, and Mocha has risen by a staggering 30%. It’s natural for some libraries to rank higher if they work in both browsers and Node.

JSLint is down to 56% from 67%, but it’s still the most popular static analysis tool. JSHint is close behind at 55%.

uglify is the most popular minimiser, which isn’t surprising given that it’s bundled with many other tools.

WebKit Inspector is the most popular debugging tool, at 79%. 500 people said they debug using node --debug, which is interesting because this is an area that I still feel needs work when developing with Node.

80% of respondents benchmark with client-side tools (1372 people). That’s probably not surprising, but given the performance-obsessed nature of certain prominent Node developers I’d have expected to see more people ticking “Benchmark scripts using a benchmarking library”.

44% of readers also write PHP, down slightly from 46% last year. C, Java, Python, and Ruby all rank around 20%, with Java edging the others out. Are there any Android developers out there?

Loading

RequireJS is the most popular module loading system – 1237 people use it. Given the sheer amount of documentation it has and the high quality site, it’s not surprising that it’s popular. Others that I didn’t mention included YUI, LABjs, and ExtJS.

Google Ajax Libraries is the most popular CDN, and it was interesting to see CloudFlare at 11%.

Project Hosting

GitHub dominates when it comes to project hosting.

At 91%, I wondered if GitHub might be at its peak. It was at 81% last year. I know there are many fellow freelancers who appreciate Bitbucket’s free private hosting, and at 20% I suspect there are people out there using both for the same reasons as me. Google Code is at 3%, so Google has got its work cut out if it wants to compete for open source projects.

Also, at 83%, GitHub was the most popular ‘project discovery’ site. This is higher than news sites (22%), which surprised me because it seems like there’s an interesting JavaScript project on Hacker News every other day.

Summary

Apart from a few surprises, 2012 has seen similar trends to last year. The new questions from Todd Bashor, Tyler Larson, and Adam Alexander were excellent, and I’m looking forward to seeing if semicolon use changes over time.

Thanks to everyone who took part in the survey!

New Streaming API for Node, Components Tutorial, Holler, GruntStart

21 Dec 2012 | By Alex Young | Comments | Tags components grunt node streams

New Streaming API for Node

In New Streaming API for Node, Isaac Schlueter outlines the issues found in Node’s current streaming API, and presents the new Node 0.10 API that addresses these problems. Although the documentation makes it clear that the stream API is “unstable”, it’s notable for two reasons: it’s built on EventEmitter, and many of Node’s core modules have stream interfaces. Streams are an integral part of Node, and it’s becoming clear that many problems are best solved with streams.

The 0.10 version of streams will cause backward compatibility issues, but this has been considered and mitigated:

For backwards compatibility with older Node programs, Readable streams switch into “old mode” when a 'data' event handler is added, or when the pause() or resume() methods are called.

Isaac has included the new stream API’s documentation in the post, and if you’re working with Node at all it’s worth reading. If you’re struggling to understand the motivation behind the changes, it boils down to pause() not really pausing, and the potential for 'data' events to be dropped before they’re ready to be consumed. I liked Isaac’s practical example of this issue:

'data' events come right away (whether you’re ready or not). This makes it unreasonably difficult to do common tasks like load a user’s session before deciding how to handle their request.

So, read A New Streaming API for Node v0.10 carefully even if you’re not working with streams directly. I’m of the opinion that you should be thinking about streams when designing Node programs, and if Node’s core developers can get them right for version 0.10 it’ll be a huge win for the platform.

Components Tutorial

The date picker from the tutorial

TJ Holowaychuk has written up a detailed tutorial on Components, about building a date picker. I’m a believer of the Components idea, and at the moment good tutorials are lacking in this area, so it’s good to see TJ writing up detailed examples like this.

There are also some screencasts available: Creating components, and Web Components - Introduction.

Holler.js

Holler.js (GitHub: bitpshr / holler, License: WTFPL, npm: holler) by Paul Bouchon is a real-time notification service. It’s distributed as a Node module with client-side code that builds on alertifyjs.

The real-time communication is handled by Faye. Paul has made a brief demonstration video to show how it works.

GruntStart

GruntStart

GruntStart (GitHub: tsvensen / GruntStart, License: MIT, GPL) by Tim Svensen is a Grunt task for building optimised websites using HTML5 Boiler Plate, jQuery, Modernizr and Respond.js. It includes a task that watches for file changes and automatically generates optimised assets.

The client-side scripts are all included, so all you need to do to get started is download GruntStart from GitHub.

Backbone.js Tutorial: Backbone.sync

20 Dec 2012 | By Alex Young | Comments | Tags backbone.js mvc node backgoog

Preparation

Before starting this tutorial, you’ll need the following:

  • alexyoung / dailyjs-backbone-tutorial at commit c1d5a2e7cc
  • The API key from part 2
  • The “Client ID” key from part 2
  • Update app/js/config.js with your keys (if you’ve checked out my source)

To check out the source, run the following commands (or use a suitable Git GUI tool):

git clone git@github.com:alexyoung/dailyjs-backbone-tutorial.git
cd dailyjs-backbone-tutorial
git reset --hard c1d5a2e7cc

Google’s Tasks API

To recap: the point of this tutorial series is to build a Backbone.js single page application that uses client-side JavaScript to communicate with Google’s authentication and to-do list APIs. Got that? Good!

Google provides access to our to-do lists through two APIs:

When loading Google’s JavaScript, the browser is bestowed with a global called gapi that provides access to various objects and methods. In the last part, I quietly included a call to gapi.client.load that loads the tasks API:

gapi.client.load('tasks', 'v1', function() { /* Loaded */ });

This can be found in app/js/gapi.js. The remaining challenge before building the interface is to implement a new Backbone.sync method that uses gapi to communicate with the Tasks and Tasklists APIs.

Backbone.sync Structure

I’ve already talked about the overall structure of Backbone.sync in part 2. The pattern I’ll use in these tutorials is fairly generic, so you could use the same approach to communicate with something other than Google’s APIs.

The sync method itself takes three arguments, the first of which is the method (create, update, delete, and read). We need to map method to something Google’s API can understand.

This is what we’ve got so far:

Backbone.sync = function(method, model, options) {
  options || (options = {});

  switch (method) {
    case 'create':
    break;

    case 'update':
    break;

    case 'delete':
    break;

    case 'read':
    break;
  }
};

Google’s Tasks API methods map to the Backbone method argument like this:

Google Tasks APIBackbone.sync MethodDescription
insertcreateCreate a new task.
updateupdateUpdate an existing task.
deletedeleteDelete a task.
listreadGet a list of tasks.

Even though Google’s API doesn’t look like the Rails 3-based RESTful API that Backbone.js is designed for out of the box, it’s still very close.

Making Requests with gapi

The gapi object makes requests using this pattern:

  • Call one of the gapi.client.tasks methods with the request content to get a request object
  • Call request.execute with a callback to send the request
  • The callback receives a response object, much like a standard Ajax request

Here’s what this looks like in reality:

var requestContent = {}
  , request
  , gapiResource;

gapiResource = 'tasks';
requestContent['tasklist'] = tasklistId; // Assuming we have one
requestContent['resource'] = model.toJSON();

// 'insert' is for creating new tasks
request = gapi.client.tasks[gapiResource].insert(requestContent);

// Send the request to the API
request.execute(function(res) {
  // Handle the response
});

Looking at this, it’s clear that we need two models: Task and TaskList. There also need to be two corresponding collections: Tasks and TaskLists.

Backbone models and collections have URLs – these are used for making API requests. Similarly, Google’s APIs have URLs: tasks and tasklists, so by using the model URL Backbone.sync can determine which API resource is required for a given request.

Models

Create a new directory called app/js/models and add task.js:

define(function() {
  var Task = Backbone.Model.extend({
    url: 'tasks'
  });

  return Task;
});

You’ll also want to create a app/js/models/tasklist.js:

define(function() {
  var TaskList = Backbone.Model.extend({
    url: 'tasklists'
  });

  return TaskList;
});

Collections

Create another new directory called app/js/collections and add tasklists.js:

define(['models/tasklist'], function(TaskList) {
  var TaskLists = Backbone.Collection.extend({
    model: TaskList
  , url: 'tasklists'
  });

  return TaskLists;
});

We’re going to use the TaskList collection later on to load your task lists.

Making API Requests

Open up app/js/gapi.js and add a new line after line 36:

app.views.auth.$el.hide();
$('#signed-in-container').show();
self.trigger('ready'); // This one

This 'ready' event will be used to signify that authentication was successful, and the Tasks API is ready for use. Next, add the following two lines to Backbone.sync, inside the read switch case:

case 'read':
  var request = gapi.client.tasks[model.url].list(options.data);
  Backbone.gapiRequest(request, method, model, options);
break;

This code creates a request, and then Backbone.gapiRequest will execute it and delegate the response.

Here’s the most basic Backbone.gapiRequest implementation:

Backbone.gapiRequest = function(request, method, model, options) {
  var result;
  request.execute(function(res) {
    if (res.error) {
      if (options.error) options.error(res);
    } else if (options.success) {
      result = res.items;
      options.success(result, true, request);
    }
  });
};

All it does is run request.execute, which is provided by Google, and then maps the result to be compatible with Backbone’s API by running the success and error callbacks.

Just so you can see something is really happening, open app/js/app.js and make it load the TaskLists collection by changing the define invocation at the top:

define([
  'gapi'
, 'views/app'
, 'views/auth'
, 'collections/tasklists'
],

function(ApiManager, AppView, AuthView, TaskLists) {

Now add this to the connectGapi method:

this.apiManager.on('ready', function() {
  self.collections.lists.fetch({ data: { userId: '@me' }, success: function(res) {
    _.each(res.models, function(model) {
      console.log(model.get('title'));
    });
  }});
});

That code uses Underscore’s each method to iterate over each “model” returned by Backbone.sync, which is called by the TaskList collection.

Run the server with npm start, and visit http://localhost:8080. If you run it in a browser that supports console, then you should see your task lists printed out.

My task lists.

If you’ve got this working then you’re not far off building a real world Backbone.js app that communicates with Google’s APIs. The same concepts can be applied to other Google JavaScript APIs.

Summary

The full source for this tutorial can be found in alexyoung / dailyjs-backbone-tutorial, commit fcd653ec6.

Substack's Musical Node Modules

19 Dec 2012 | By Alex Young | Comments | Tags node modules audio music
Prerequisites: Install gnuplot and SoX to follow along.

James Halliday, otherwise known as “substack”, has been making what he calls computer generated beepstep using two new modules: baudio (npm: baudio, License: MIT) and plucky (npm: plucky, License: MIT).

The baudio module returns a readable stream that generates raw audio data. It requires SoX to play or record audio, which should be installable from your package manager (Debian has it, and so does Homebrew).

The callback passed to the baudio function receives two arguments: t and i – the time in seconds, and a counter. The callback will be run using process.nextTick to generate a stream of audio data. The audio data will be passed to SoX for playback or recording using child_process.spawn.

The audio data itself is where things get interesting. The baudio stream is sent directly into SoX through SoX’s “pipeline” mode, in which audio data is read from standard input, using the “s16” format – it’s streams all the way down! Internally, baudio converts the float values returned from the callback into integers, which are written to a buffer using Node’s buf.writeInt16LE method.

Your callback should generate floating point values between -1.0 and 1.0. By default, baudio is set to use a frequency of 44 kHz – that’s 44,000 values a second. This is close to CD quality (44.1 kHz).

Unless you’re well-versed in audio programming, generating sounds with baudio is going to be hard work. To help you understand what’s going on, I’ve written a small example that uses gnuplot to visualise the output.

First, install baudio:

npm install baudio

And then create a file called baudio-simple.js:

var baudio = require('baudio')
  , out = process.stdout
  , note = 1.0
  ;

var b = baudio(function(t, i) {
  var value = Math.sin(Math.PI * t * 261.626);
  out.write(value.toString() + '\n');
  return value;
});

setTimeout(function() {
  b.end();
}, 1000);

b.play();

This file can be run with node baudio-simple.js > audio.dat (the redirection is important for generating the graphs), and if you’ve got SoX installed you’ll get a sound.

Now you’re going to write a bit of gnuplot. Create a file called baudio-plot with this script:

#!/usr/bin/env gnuplot

set terminal png size 530,420
set output "baudio.png"
plot "audio.dat" using 0:1 with lines

Now make it executable, and run it:

chmod 700 baudio-plot
./baudio-plot

It should generate a file called baudio.png with a second’s worth of audio data plotted.

A graph of baudio's output using one second of audio.

If you’re looking at Math.sin in the example code and wondering why there isn’t a beautiful sweeping sine wave, then the reason is simple: there’s too much data. Let’s try ending the output earlier:

var baudio = require('baudio')
  , out = process.stdout
  , note = 1.0
  ;

var b = baudio(function(t, i) {
  if (i > 100) b.end();
  var value = Math.sin(Math.PI * t * 261.626);
  out.write(value.toString() + '\n');
  return value;
});

b.play();

Now your graph should look like a wave, but you won’t hear much sound:

A much shorter sample shows the output really is a sine wave.

Wave Period and Amplitude

The simple example I’ve used above is focused on controlling the “wave period”, or the pitch of the output. To demonstrate this, try changing 261.626 to 60.0:

Some sub-bass.

Now the output is a lower pitch, and the graph makes this clear because you can see there are less cycles in the same amount of time. So we’ve mastered pitch, but what about volume?

It’s actually easy once you know what the wave equation is doing. The generalised equation is A sin(t - K) + b (from Amplitude on Wikipedia). In programmer-speak, this equation can be written as A * sin(t - K) + b, where A is the “peak amplitude of the wave”, t is time (which we already know baudio gives us), and K and b are offsets for the wave (which I’m not going to talk about here).

That gives rise to the following example that allows volume to be controlled by adding a variable, vol, for A:

var baudio = require('baudio')
  , out = process.stdout
  , note = 1.0
  , vol = 0.1
  ;

var b = baudio(function(t, i) {
  if (i > 100) b.end();
  var value = vol * Math.sin(Math.PI * t * 261.626);
  out.write(value.toString() + '\n');
  return value;
});

b.play();

The graph is now appropriately smaller:

A quieter audio sample, plotted with set yrange [-1.0:1.0] to correct the axis.

More Fun Stuff

If you’ve managed to get gnuplot and SoX installed and played around with these examples, then there’s more! First, try taking a look at plucky, which can be used to make “arrangements” of callbacks that generate different channels of audio. Also, James wrote beepstep.js which is a much more involved example than anything I’ve talked about here.

And, James tweets about this stuff, so follow @substack if you’re into streams and audio hacking.

jQuery Roundup: 1.9, UI 1.10, Maskew

18 Dec 2012 | By Alex Young | Comments | Tags jquery plugins mobile effects
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

jQuery 1.9 Beta 1

jQuery 1.9 Beta 1 has been released, and this version removes previously deprecated features so you’ll want to pay attention. Fortunately, Dave Methvin has been working on jquery / jquery-migrate, which is a plugin for figuring out which deprecated features are being used in your projects. The development version shows console warning messages, and these are stored in jQuery.migrateWarnings for browsers that don’t support console. There’s a full list of the warnings in jQuery Migrate Plugin - Warning Messages.

The focus of 1.9 has been API cleanup, and there’s also a jQuery 1.9 Upgrade Guide, where these API changes have been documented.

jQuery UI 1.10 Beta

jQuery UI 1.10 Beta is out. This version features a new API for the Dialog widget, and a redesigned Progressbar API.

There are major API changes in 1.10, so if you haven’t updated to 1.9 yet then you might want to read through the 1.9 upgrade guide.

Maskew

Get skewed.

Maskew (GitHub: dmotz / maskew, License: MIT) by Dan Motzenbecker is a small plugin that can skew elements along a specified angle. It has an optional jQuery plugin, but also has a simple prototype class API. It has support for touchscreen events, specified by passing { touch: true } as an argument.

Dan has included the build script and some tests.

JavaScript Developer Survey 2012

17 Dec 2012 | By Alex Young | Comments | Tags community surveys
Note: This survey has now closed. The results are here.

Welcome to the JavaScript Developer Survey 2012. To complete the survey, visit JavaScript Developer Survey 2012 or fill out the embedded form in this post.

I’ve includes some question suggestions from readers Todd Bashor, Tyler Larson, and Adam Alexander.

If you can share this survey on social networking sites, or your favourite news site, then I’d appreciate it. As always this survey is open in the sense that responses are public, so you can use the data to develop related open source or commercial projects.

This survey has closed.

Continuum, Analytics.js, MaskJS

14 Dec 2012 | By Alex Young | Comments | Tags libraries templates browser

Continuum

Continuum (GitHub: Benvie / continuum, License: MIT, npm: continuum) by Brandon Benvie is an ES6 virtual machine written in ES3. By using Esprima to parse a given source file, it generates bytecode which is then executed within an ES6 runtime environment.

If this doesn’t sound enough like science fiction to you, then think about it like this: this project will run your ECMAScript 6 code inside its own space-time continuum that allows legacy browsers to support ECMAScript 6 features.

Brandon has already implemented a slew of ES6 features, but hasn’t yet added support for array comprehensions, tail call optimisation, or the binary data API. What you do get, however, is destructuring assignment, spread in arguments and array initializers, “rest” parameters, classes and super, arrow functions, and even Map, Set, and WeakMap.

If you want to get an idea of how this project works, take a look at the engine/assembler.js and engine/runtime.js files to see the opcodes and how the stack is used.

Analytics.js

Analytics.js (GitHub: segmentio / analytics.js, License: MIT) from Segment.io is a simplified API for supporting various web analytics services, including Google Analtyics, KISSmetrics, Mixpanel, and Chartbeat.

It provides a single API for defining events that should be tracked, allowing you to focus on getting the data out of activities on your site without becoming bogged down in a given service’s implementation peculiarities.

Segment.io also made Socrates.io, which seems to be very popular. I recommend keeping an eye on the GitHub Segment.io account for more cool projects.

MaskJS

MaskJS (GitHub: tenbits / MaskJS, License: MIT) by Alexander Kit is a template engine for Node and browsers. The author has built it with performance and mobile devices in mind, and has a jsperf benchmark that compares it against other template engines.

It supports custom tags, which are designed to help encapsulate markup into reusable components, and the author has created some for two-way data binding. The best way to get a feel for the markup style and API is to check out the MaskJS examples.

Backbone.js Tutorial: Authenticating with OAuth2

13 Dec 2012 | By Alex Young | Comments | Tags backbone.js mvc node backgoog

In Part 2: Google’s APIs, I laid the groundwork for talking to Google’s JavaScript APIs. Now you’re in a position to start talking to the todos API, but first a user account is required.

Preparation

Before starting this tutorial, you’ll need the following:

  • alexyoung / dailyjs-backbone-tutorial at commit 9d09a66b1f
  • The API key from part 2
  • The “Client ID” key from part 2
  • Update app/js/config.js with your keys (if you’ve checked out my source)

To check out the source, run the following commands (or use a suitable Git GUI tool):

git clone git@github.com:alexyoung/dailyjs-backbone-tutorial.git
cd dailyjs-backbone-tutorial
git reset --hard 9d09a66b1f

Google’s OAuth 2.0 Client-side API

Open app/js/gapi.js and take a look at lines 11 to 25. There’s a method, provided by Google, called gapi.auth.authorize. This uses the “Client ID” and some scopes to attempt to authenticate. I’ve already set the scopes in app/js/config.js:

config.scopes = 'https://www.googleapis.com/auth/tasks https://www.googleapis.com/auth/userinfo.profile';

This tells the authentication system that our application would like to access the user’s profile and Gmail tasks. Everything is almost ready to work, but two things are missing: an implementation for handleAuthResult and an interface.

Templates

RequireJS can load templates by using the text plugin. Download text.js from GitHub and save it to app/js/lib/text.js.

This is my preferred technique for handling templates. Although this application could easily fit into a monolithic index.html file, breaking up projects into smaller templates is more manageable in the long run, so it’s a good idea to get used to doing this.

Now open app/js/main.js and add the text plugin to the paths property of the RequireJS configuration:

paths: {
  text: 'lib/text'
},

Finally, add this to app/js/config.js:

_.templateSettings = {
  interpolate: /\{\{(.+?)\}\}/g
};

This tells Underscore’s templating system to use double curly braces for inserting values, otherwise known as interpolation.

The app needs some directories to store template-related things:

  • app/js/views – This is for Backbone.js views
  • app/js/templates – Plain HTML templates, to be loaded by the views
  • app/css

The app/index.html file needs to load the CSS, so add a link tag to it:

<link rel="stylesheet" href="css/app.css">

And create a suitable CSS file in app/css/app.css:

#sign-in-container, #signed-in-container { display: none }

The application will start up by hiding both the sign-in button and the main content. The oauth API will be queried for existing user credentials – if the user has already logged in recently their details will be stored in a cookie, so the views need to be configured appropriately.

Templates

The templates aren’t particularly remarkable at this stage, just dump this into app/js/templates/app.html:

<div class="row-fluid">
  <div class="span2 main-left-col" id="lists-panel">
    <h1>bTask</h1>
    <div class="left-nav"></div>
  </div>
  <div class="main-right-col">
    <small class="pull-right" id="profile-container"></small>
    <div>
      <div id="sign-in-container"></div>
      <div id="signed-in-container">
        <p>You're signed in!</p>
      </div>
    </div>
  </div>
</div>

This template shows some things that we won’t be using yet, just ignore it for now and focus on sign-in-container and signed-in-container.

Next, paste the following into app/js/templates/auth.html:

<a href="#" id="authorize-button" class="btn btn-primary">Sign In with Google</a>

The auth.html template will be inserted into sign-in-container. It’s very simple at the moment, I only really included it for an excuse to create extra Backbone.js views so you can see how it’s done.

Backbone Views

These templates need corresponding Backbone.js views to manage them. This part demonstrates how to load templates with RequireJS and render them. Create a file called app/js/views/app.js:

define([
  'text!templates/app.html'
],

function(template) {
  var AppView = Backbone.View.extend({
    id: 'main',
    tagName: 'div',
    className: 'container-fluid',
    el: 'body',
    template: _.template(template),

    events: {
    },

    initialize: function() {
    },

    render: function() {
      this.$el.html(this.template());
      return this;
    }
  });

  return AppView;
});

The AppView class doesn’t have any events yet, but it does bind to an element, body, and load a template: define(['text!templates/app.html']. The text! directive is provided by the RequireJS “text” plugin we added earlier. The template itself is just a string that contains the corresponding HTML. It’s rendered by binding it to the Backbone.View, and then calling jQuery’s html() method which replaces the HTML within an element: this.$el.html(this.template());.

The AuthView is a bit different. Create a file called app/js/views/auth.js:

define(['text!templates/auth.html'], function(template) {
  var AuthView = Backbone.View.extend({
    el: '#sign-in-container',
    template: _.template(template),

    events: {
      'click #authorize-button': 'auth'
    },

    initialize: function(app) {
      this.app = app;
    },

    render: function() {
      this.$el.html(this.template());
      return this;
    },

    auth: function() {
      this.app.apiManager.checkAuth();
      return false;
    }
  });

  return AuthView;
});

The app object is passed to initialize when AuthView is instantiated (with new AuthView(this) later on). The reason I’ve done this is to allow the view to call the required authentication code from ApiManager. This could also be handled with events, or many other ways – I just wanted to show that we can initialise views with values just like any other class.

App Core

The views need to be instantiated and rendered. Open app/js/app.js and change it to load the views using RequireJS:

define([
  'gapi'
, 'views/app'
, 'views/auth'
],

function(ApiManager, AppView, AuthView) {
  var App = function() {
    this.views.app = new AppView();
    this.views.app.render();

    this.views.auth = new AuthView(this);
    this.views.auth.render();

    this.connectGapi();
  }

The rest of the file can remain the same. Notice that the order these views are rendered is important – AuthView won’t work unless it has some of AppView’s tags available. A better way of modeling this might be to move AuthView inside AppView so the dependency is reflected. You can try this yourself if you want to experiment.

Authentication Implementation

The app/js/gapi.js file still doesn’t have the handleAuthResult function, so nothing will work yet. Here’s the code to handle authentication:

function handleAuthResult(authResult) {
  var authTimeout;

  if (authResult && !authResult.error) {
    // Schedule a check when the authentication token expires
    if (authResult.expires_in) {
      authTimeout = (authResult.expires_in - 5 * 60) * 1000;
      setTimeout(checkAuth, authTimeout);
    }

    app.views.auth.$el.hide();
    $('#signed-in-container').show();
  } else {
    if (authResult && authResult.error) {
      // TODO: Show error
      console.error('Unable to sign in:', authResult.error);
    }

    app.views.auth.$el.show();
  }
}

this.checkAuth = function() {
  gapi.auth.authorize({ client_id: config.clientId, scope: config.scopes, immediate: false }, handleAuthResult);
};

The trick to a smooth sign-in flow is to determine when the user is already signed in. If so, then authentication should be handled transparently, otherwise the user should be prompted.

The handleAuthResult function is called by gapi.auth.authorize from the checkAuth function, which isn’t displayed here (it’s before handleAuthResult in the source file if you want to check it). The this.checkAuth method is different – this is a public method that calls gapi.auth.authorize with immediate set to false, while the other invocation calls it with true.

The immediate option is important because it determines whether a popup will be displayed or not. I’ve used it to check if the user is already signed in, otherwise it’s called again with immediate: false and will display a suitable popup so the user can see what permissions the app wants to use:

Authentication process

I designed it this way based on the Google APIs Client Library for JavaScript documentation:

“The standard authorize() method always shows a popup, which can be a little jarring if you are just trying to refresh an OAuth 2.0 token. Google’s OAuth 2.0 implementation also supports “immediate” mode, which refreshes a token without a popup. To use immediate mode, just add “immediate: true” to the login config as in the example above.”

I’ve also changed the ApiManager class to store a reference to App:

// Near the top of gapi.js
var app;

function ApiManager(_app) {
  app = _app;
  this.loadGapi();
}

Summary

In this tutorial you’ve seen how to use Google’s APIs to sign into an app you’ve previously registered with the Google API Console (documented in part 2). It might seem like a lot of work to get RequireJS, Backbone.js, and Google OAuth working together, but think about what this has achieved: 100% client-side scripting that can authenticate with existing Google accounts.

If I’ve missed anything here, you can check out the full source from commit c1d5a2e7c.

Node Roundup: thin-orm, node-tar.gz, connect-bruteforce

12 Dec 2012 | By Alex Young | Comments | Tags node modules middleware express compression databases
You can send in your Node projects for review through our contact form or @dailyjs.

thin-orm

thin-orm (License: MIT, npm: thin-orm) by Steve Hurlbut is a lightweight ORM module for SQL databases with a MongoDB-inspired API:

var orm = require('thin-orm');

orm.table('users')
   .columns('id', 'login', 'firstName', 'lastName', 'createdAt');

It’s designed to be used with existing libraries, like pg and sqlite3, so you’ll need one of those modules installed to use it.

thin-orm currently supports the following features:

  • Filtering
  • Sorting
  • Pagination
  • Joins
  • Optional camelCase property-to-field mapping
  • SQL injection protection

Steve has included Nodeunit tests that cover the basic functionality, and some integration tests for PostgreSQL and SQLite.

node-tar.gz

node-tar.gz (License: MIT, npm: tar.gz) by Alan Hoffmeister is a tar helper module and command-line utility, built with Node’s zlib module, tar, and commander.

The module can be used to easily tar and compress a folder, and it will install a targz script that supports the zxvf flags. There are also Vows tests.

connect-bruteforce

connect-bruteforce (License: GPLv2, npm: connect-bruteforce) by Pedro Narciso García Revington provides middleware that can help prevent bruteforce attacks. It will add a small delay to requests when an attack is detected.

The author has written a useful example that requires captcha validation after a successive number of validation failures: express-recaptcha.

For a simpler example, see express-hello-world.

The project includes Mocha tests.

jQuery Roundup: SocialCount, Literally Canvas, Socrates

11 Dec 2012 | By Alex Young | Comments | Tags jquery plugins social markdown apps images
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

SocialCount

Social buttons can slow down page loading times due to a variety of reasons. One solution is to lazy load them, and this is exactly what the SocialCount (GitHub: filamentgroup / SocialCount, License: MIT) from Filament Group does. It can show “like” style buttons, counts, and lazy load the social network’s original buttons.

It’s designed using progressive enhancement techniques, and is tested against IE 7+, as well as the other major browsers, and various touchscreen devices. It also includes QUnit tests.

Literally Canvas

Drawing with a trackpad is tricky business.

Literally Canvas (GitHub: literallycanvas / literallycanvas, License: BSD) by Stephen Johnson and Cameron Paul is a drawing widget built with jQuery and Underscore.js. It has some basic drawing tools and can upload images to imgur.

The plugin accepts an options object that can be used to enable or disable certain features:

$('.literally').literallycanvas({
  backgroundColor: 'rgb(255, 0, 0)', // default rgb(230, 230, 230)
  keyboardShortcuts: false,          // default true
  sizeToContainer: false,            // default true
  toolClasses: [LC.Pencil]           // see coffee/tools.coffee
});

Socrates

Real-time Markdown editing with Socrates.

Socrates (GitHub: segmentio / socrates, License: MIT) by Ilya Volodarsky and Ian Storm Taylor is a Markdown editor and previewer. It’s built with jQuery, Backbone.js, and a client-side Markdown parser by Christopher Jeffrey.

The data is stored in Firebase, so you’ll need an account with Firebase to install your own instance of Socrates.

Extender, Gridy.js, grunt-reduce

10 Dec 2012 | By Alex Young | Comments | Tags libraries build grunt tv browser

Extender

Extender (GitHub: doug-martin / extender, npm: extender, License: MIT) by Doug Martin is a library for making chainable APIs. It works as a Node module or with RequireJS.

Extender has a define method that accepts a function and an object with methods that will form the API:

function isString(obj) {
  return !isUndefinedOrNull(obj) && (typeof obj === "string" || obj instanceof String);
}

var myExtender =
  .define(isString, {
    multiply: function(str, times) {
      var ret = str, i;
      for (i = 1; i < times; i++) {
        ret += str;
      }
      return ret;
    },
    toArray: function(str, delim) {
      delim = delim || '';
      return str.split(delim);
    }
  });

myExtender('hello').multiply(2).value(); // hellohello

The author has included tests and lots of examples. Although making chainable APIs is pretty straightforward, Extender might be a more explicit and testable way to do it.

Gridy.js

Gridy.js

In the UK only one of my favourite shows is on Netflix. The situation might be better in the US with Hulu, but if you’re a cult TV fan outside of the US finding content can be challenging. Even with a dearth of legitimate content sources, I’ll always prefer hacking my TV to using locked down devices – I had loads of fun this weekend with a Raspberry Pi and open source media projects.

One thing that’s often lacking is cool web interfaces for media software. Igor Alpert sent in Gridy.js (GitHub: ialpert / gridy.js), which is a library designed for building media browser interfaces. It includes tools for carousels, grids, and sliders.

Igor said he’s tested it with the Samsung SDK, Opera TV, and Google TV for the LG and Vizio platforms.

grunt-reduce

grunt-reduce by Peter Müller is a Grunt task for AssetGraph and other related projects from One.com. AssetGraph is a Node-based module for optimising web pages. By adding grunt-reduce to your project, you can bundle and minify assets, rename assets to MD5-sums of their content, optimise images, and even generate automatic CSS sprites.

Although AssetGraph doesn’t currently work with AngularJS, Peter notes that this is being addressed: #84: Support AngularJS templates.

JavaScript Survey 2012, Gitgraph, ES6 Proxies

07 Dec 2012 | By Alex Young | Comments | Tags ES6 git graphs Canvas survey community

JavaScript Survey 2012: RFC

I’m currently researching the next JavaScript Developer Survey. I’d like feedback on questions. If there’s anything you’d strongly like to see in the survey, please contact me and I’ll see if I can incorporate it.

Previous surveys can be found here:

In general, the surveys try to determine:

  • How many readers are client-side or server-side developers
  • Whether or not readers write tests
  • Other languages used (C#, Java, Objective-C, PHP, Ruby, Python, etc.)

It’s not necessarily used to design content for DailyJS – the results are shared with the community benefit everyone.

Gitgraph

Gitgraph (GitHub: bitpshr / Gitgraph, License: WTFPL) by Paul Bouchon is a Canvas-based GitHub participation graph library. It’s based around a constructor function that accepts arguments for things like GitHub username, width, height, and colours:

var graph = new Gitgraph({ 
    user        : 'nex3',                // any github username
    repo        : 'sass',                // name of repo
    domNode     : document.body,         // (optional) DOM node to attach to 
    width       : 800,                   // (optional) graph width
    height      : 300,                   // (optional) graph height
    allColor    : "rgb(202, 202, 202)",  // (optional) color of user's participation
    userColor   : "rgb(51, 102, 153)",   // (optional) color of total participation
    background  : "white",               // (optional) background styles
    showName    : true                   // (optional) show or hide name of user / repo
});

The author wrote some background on it in GitHub Graphs Fo’ Errbody, because he had to wrap missing API functionality with a proxy.

Multiple Inheritance in ES6 with Proxies

Multiple Inheritance in ES6 with Proxies is an introduction to ES6 proxies by Jussi Kalliokoski. The author’s example uses EventEmitter, which I find useful because multiple inheritance with EventEmitter is something I’ve seen typically implemented using a for loop to copy properties.

The Proxy solution isn’t far off that approach and requires more code, but it’s worth reading if you’re struggling to understand proxies.