I made a little sign-up form example with React.

I built it in RequireBin. The main react model in isn’t working in RequireBin and I’m working to get it fixed. In the meantime I’ve published benatkin-react to npm which makes the minimal changes needed to get it to work (none to the code, just to the packaging).

The sign-up form I made has validation which highlights invalid fields with red after an attempt has been made to enter it in correctly.

This month my goal is to post a small JavaScript project every day of the month. Today’s project is an angular.js app for jumping between paragraphs using the keyboard. Besides navigating between paragraphs it can show paragraphs before or after the current paragraph without leaving the page. This could help if the reader needs to recall a detail from the last paragraph in order to fully understand the current paragraph.

I used these resources to help me get it done:

  • How to listen for key presses with AngularJS – showed me that I wanted was keydown events on the body tag using ng-keydown
  • 5apps – a lot like GitHub pages with Jekyll turned off, except I don’t need to create another branch. Unlike Heroku, free apps don’t go to sleep.

I tried out hood.ie today after hearing about it a few times and I think it’s worth giving a shot, if you’re interested in rich web applications. It’s easy to install for what it does, which is set up a local node.js and couchdb environment with an admin interface. Deployment looks like it will be really easy, too.

If you want to use Backbone.js’s extend function on your own class, all you have to do is this:

var LightModel = function(attributes, options) {
  this.attributes = _.extend({}, attributes);
}

_.extend(LightModel.prototype, Backbone.Events, {
  get: function(key) { return this.attributes[key]; },
  set: function(key_or_values, value) {
    if (typeof key_or_values == 'string') {
      this.attributes[key_or_values] = value;
    } else {
      _.extend(this.attributes, key_or_values);
    }
  }
});

LightModel.extend = Backbone.extend;

Backbone’s extend function is the same between Backbone’s classes. It just uses the prototype it was called with. MyModel1 and MyModel2 in the following example would be equivalent:

var MyModel1 = Backbone.Model.extend({});
var MyModel2 = Backbone.View.extend.call(Backbone.Model, {});

Here’s a copy of the email I sent to the CouchDB users mailing list:

I made a couple of npm (node.js) modules for editing CouchDB design documents that involves fewer files than python CouchApp, but like python CouchApp supports two-way sync. The function source is left intact when converting between JavaScript source and JSON. The JavaScript source version just shows it in an embedded function expression, which makes it syntax highlightable.

http://benatkin.com/2012/09/04/js2json-and-json2js/
https://github.com/benatkin/js2json
https://github.com/benatkin/json2js

Here’s a quick example. If I stick this in books.js:

module.exports = {
  "views": {
    "author": {
      "map": function(doc) {
        if (doc.type == 'book')
          emit(doc.author, null);
      }
    },
    "title": {
      "map": function(doc) {
        if (doc.type == 'book')
          emit(doc.title, null);
      }
    }
  }
}

…and run this (after npm install json2js js2json):

var js2json = require('js2json');
var json2js = require('json2js');
var fs = require('fs');

var jsSource = fs.readFileSync('books.js', 'utf8');
var jsonValue = js2json.convert(jsSource);
fs.writeFileSync('books.json', JSON.stringify(jsonValue, null, 2) + "\n");
var jsSourceFromJson = json2js.convert(jsonValue);
fs.writeFileSync('books-from-json.js', jsSourceFromJson + "\n");

…I get the following in books.json:

{
  "views": {
    "author": {
      "map": "function(doc) {\n  if (doc.type == 'book')\n
emit(doc.author, null);\n}"
    },
    "title": {
      "map": "function(doc) {\n  if (doc.type == 'book')\n
emit(doc.title, null);\n}"
    }
  }
}

…and books-from-json.js is exactly the same as books.js.

I explain it more in my blog post (linked at the top of this message). I need to add a cli tool that syncs, a way to handle attachments, and a way to handle embedded multiline strings for it to be a full-featured design doc editor. I have much bigger plans for this, though: I want to break up CouchApps into a bunch of smaller documents! The source and tests for these two modules is programmed in the same style. I think storing functions in JSON makes CouchDB just a little bit like Smalltalk, with a much more familiar language.

Thanks for reading. Feedback welcome and appreciated.

I made a couple of small node.js modules to help me develop couchapps.

CouchApp is two things: a concept and a tool. The concept is an application that runs on CouchDB, using its API. The API has three basic components for presenting data (it has others for editing data but that isn’t covered in this post):

  • views: A view in CouchDB is a Map and optionally a Reduce function, which enables indexing JSON documents using the powerful MapReduce programming model.
  • lists: A list is a function that renders documents from a view, into an any format (commonly HTML).
  • shows: A show function renders a single document, into any format.

With these simple functions, a blog or a photo gallery can be made viewable. The URLs can get a bit awkward, but CouchDB provides a rewrites feature to solve it.

These functions go into a CouchDB design document. CouchDB is a JSON database, and a design document is a JSON document that contains functions as strings. A single design document, with attachments for CSS, which can be served directly to the web browser, can provide access to data without relying on client-side JavaScript (instead using server-side JavaScript).

The tool is a python command-line utility that maps a CouchDB design document to a directory structure. It can clone a design document directly from the database. It breaks it into a lot of little files, including a separate JavaScript file for each function.

This can be a lot of files, when there is one file for each function. Here is the CouchOne pages wiki CouchApp. It has a lot of views.

Mikeal Rogers had perhaps the first solution to this problem: node.couchapp.js. It runs on node.js and allows programmatic building of a design document, and puts functions in strings to prepare the JSON using Function.toString(). This loses the python CouchApp’s advantage of being able to go back and forth from file to CouchDB without losing anything.

I wanted something that could sync back and forth and is more like the original JSON than python’s CouchApp. To make it usable, I need functions shown across multiple lines with syntax highlighting. My hack was to convert the JavaScript to JSON. With CommonJS I can convert JSON to JavaScript easily, just by adding module.exports = to the front of the file. I can then replace the function strings with the direct value of the strings. To go from JavaScript to JSON I need to get the original function source. With JavaScript’s fn.toString(), where fn is a function, I get the source without the comments. I want the comments. It also isn’t indented properly. With Esprima I wrote code to extract the raw function source and fix up the indentation. Examples of this are in the READMEs of the two projects, json2js and js2json.

The projects below are still in early development and barely tested, but I’m putting them to use right now, by finally putting one of my fancy domain names to good use. ;) In the meantime, if this interests you, please check them out and give me feedback.

Repositoryjson2js
Repositoryjs2json

Update: @twitinsin points out that it’s still useful in the console for quickly declaring multiple variables.

I developed the habit of always using var when I write JavaScript long ago. At some point I got in the habit of typing var even when I’m using a JavaScript console in node or in a browser. After examining the issues I’ve decided to break that habit.

I think I got in the habit of this because I came to appreciate explicit variable declaration, and decided to gladly pay the tax. The four extra characters, including the space, isn’t bad. But it doesn’t serve a useful purpose in short console sessions. Without var, it’s still valid JavaScript, that will run in node.js and in any browser. It won’t pass JSHint and JSLint, which is why it should always be added before delivering code.

If this gets me to be just a little quicker to fire up a REPL (a more generic term which includes the JavaScript console), it will be an improvement.

Connect has a session middleware that has a pluggable API for session storage. There is a session store for redis, written by TJ Holowaychuk, who maintains both connect and express. There are also session stores for CouchDB, MongoDB, and postgresql that look to be well-maintained and ready for production use.

These are great, but I wanted to store my session data in cookies, because the amount of session data I plan to use is tiny, and because my app is designed to handle high-latency CouchDB database connections gracefully.

I had a hard time finding a session store that stores session data in the cookies. The session middleware uses cookies, but it uses them to store the keys to access the session data, not the session data itself. I found an example but no actively maintained session store for cookies.

After some more searching, I found that the way to store sessions in cookies is to use a whole different middleware that comes with connect! It’s called cookieSession. To use it all I have to do is add this code snippet, and ensure that I have session_secret set in my app settings:

app.use(connect.cookieParser(app.set('session_secret')));
app.use(connect.cookieSession());

When using cookie sessions it’s important that the cookie data is small and that the cookie is signed using a session secret, to prevent session fixation. This is documented in the excellent Ruby On Rails Security Guide. Even if you aren’t using RoR I recommend reading it.

I published a node.js package to npm called br-jquery, which contains jQuery and provides an alternate path to downloading jQuery and putting it in a repository when starting a jQuery project. It is a lot like jquery-browserify, but it contains a newer version of jQuery (1.7.1) and has the minified version as well. Additionally it has a build script which fetches jQuery and a full example.

Browserify creates bundles from node.js-style CommonJS modules. It stubs out some core functionality so node.js modules with minimal dependencies can be used in the browser. Here is some JavaScript taken from the example, that creates a bundle:

var js = require('browserify')({
  require: {jquery: 'br-jquery'},
  entry: 'hello.js'
}).bundle()

The require property is used to , and the entry property is used to include a module that will be run when the bundle is loaded. The entry module starts by requiring jQuery:

var $ = require('jquery');
$(function() {
  // manipulate the DOM here...
});

I really like the browserify way of doing things. Instead of adapting browser code to run on the server, it adapts server code to run on the browser!

Repositorybr-jquery
Repositoryjquery
Ownerjquery

I’ve been reading quite a bit about parsing and templating in ruby as I attempt to port a templating engine from JavaScript to Ruby. Here are some scattered links:

Jison

Jison is a parser generator for JavaScript that has separate lex and bnf definitions. It’s used by Handlebars.js.

Repositoryjison
Ownerzaach

Treetop

Treetop is a parser generator for Ruby. It’s installed with Ruby On Rails, through the mail gem which is installed by ActionMailer.

Repositorytreetop

Citrus

Citrus is another promising parsing gem for Ruby. It seems to be very easy to get started with, and I like many of the design decisions.

Repositorycitrus

Temple

Temple is a templating-specific library that helps with a lot of the AST transformation. It doesn’t seem to have a CFG syntax so it seems that using treetop or citrus would make sense for complex grammars. Otherwise, strscan could be used.

Repositorytemple
Ownerjudofyr

temple-mustache

This is an implementation of a mustache renderer in . It uses strscan to generate the initial parse tree, and Temple to generate the ruby code. It supports mustache sections.

Repositorytemple-mustache
Ownerminad

Slim

Slim is a Haml-like templating library for Ruby that’s used in production by many. It uses Temple, with a line-based parser, which works well because it uses significant indentation for nesting.

Repositoryslim
Ownerstonean