How Ender Bundles Libraries for the Browser

23 Aug 2012 | By Rod Vagg | Comments | Tags ender frameworks modules libraries tutorials
This is a contributed post by Rod Vagg. This work is licensed under a Creative Commons Attribution 3.0 Unported License.

I was asked an interesting Ender question on IRC (#enderjs on Freenode) and as I was answering it, it occurred to me that the subject would be an ideal way to explain how Ender’s multi-library bundling works. So here is that explanation!

The original question went something like this:

When a browser first visits my page, they only get served Bonzo (a DOM manipulation library) as a stand-alone library, but on returning visits they are also served Qwery (a selector engine), Bean (an event manager) and a few other modules in an Ender build. Can I integrate Bonzo into the Ender build on the browser for repeat visitors?

What’s Ender?

Let’s step back a bit and start with some basics. The way I generally explain Ender to people is that it’s two different things:

  1. It’s a build tool, for bundling JavaScript libraries together into a single file. The resulting file constitutes a new “framework” based around the jQuery-style DOM element collection pattern: $('selector').method(). The constituent libraries provide the functionality for the methods and may also provide the selector engine functionality.
  2. It’s an ecosystem of JavaScript libraries. Ender promotes a small collection of libraries as a base, called The Jeesh, which together provide a large portion of the functionality normally required of a JavaScript framework, but there are many more libraries compatible with Ender that add extra functionality. Many of the libraries available for Ender are also usable outside of Ender as stand-alone libraries.

The Jeesh is made up of the following libraries, each of these also works as a stand-alone library:

  • domReady: detects when the DOM is ready for manipulation. Provides $.domReady(callback) and $.ready(callback) methods.
  • Qwery: a small and fast CSS3-compatible selector engine. Does the work of looking up DOM elements when you call $('selector') and also provides $(elements).find('selector'), $(elements).and(elements) and $(elements).is('selector').
  • Bonzo: a DOM manipulation library, providing some of the most commonly used methods, such as $(elements).css('property', 'value'), $(elements).empty(), $(elements).after(elements||html), and many more.
  • Bean: an event manager, provides jQuery-style $(elements).bind('event', callback) and others.

The Jeesh gives you the features of these four libraries bundled into a neat package for only 11.7 kB minified and gzipped.

The Basics: Bonzo

Bonzo is a great way to start getting your head around Ender because it’s so useful by itself. Let’s include it in a page and do some really simple DOM manipulation with it.

<!DOCTYPE HTML>
<html lang="en-us">
<head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <title>Example 1</title>
</head>
<body>
  <script src="bonzo.js"></script>
  <script id="scr">
    // the contents of *this* script,
    var scr = document.getElementById('scr').innerHTML

    // create a <pre></pre>
    var pre = bonzo.create('<pre>')

    // fill it with the script text, append it to body and style it
    bonzo(pre)
      .text(scr)
      .css({
        fontWeight: 'bold',
        border: 'solid 1px red',
        margin: 10,
        padding: 10
      })
      .appendTo(document.body);

  </script>
</body>
</html>

You can run this as example1, also available in my GitHub repository for this article.

This should look relatively familiar to a jQuery user – you can see that Bonzo is providing some of the important utilities you need for modifying the DOM.

Bonzo Inside Ender

Let’s see what happens when we use a simple Ender build that includes Bonzo. We’ll also include Qwery so we can skip the document.getElementById() noise, and we’ll also use Bean to demonstrate how neatly the libraries can mesh together.

This is done on the command line with: ender build qwery bean bonzo. A file named ender.js will be created that can be loaded on a suitable HTML page.

Our script becomes:

$('<pre>')
  .text($('#scr').text())
  .css({
    fontWeight: 'bold',
    border: 'solid 1px red',
    margin: 10,
    padding: 10
  })
  .bind('click', function () {
    alert('Clickety clack');
  })
  .appendTo('body');

You can run this as example2, also available in my GitHub repository for this article.

Bonzo performs most of the work here but it’s bundled up nicely into the $ object (also available as ender). The previous example can be summarised as follows:

  • bonzo.create() is now working when HTML is passed to $().
  • Qwery does the work when $() is called with anything else, in this case $('#scr') is used as a selector for the script element.
  • We’re using the no-argument variant of bonzo.text() to fetch the innerHTML of the script element.
  • Bean makes a showing with the .bind() call, but the important point is that it’s integrated into our call-chain even though it’s a separate library. This is where Ender’s bundling magic shines.
  • bonzo.appendTo() takes the selector argument which is in turn passed to Qwery to fetch the selected element from the DOM (document.body).

Also important here, which we haven’t demonstrated, is we can do all of this on multiple elements in the same collection. The first line could be changed to $('<pre></pre><pre></pre>') and we’d end up with two blocks, both responding to the click event.

Removing Bonzo

It’s possible to pull Bonzo out of the Ender build and manually stitch it back together again. Just like we used to do with our toys when we were children! (Or was that just me?)

First, our Ender build is now created with: ender build qwery bean (or we could run ender remove bonzo to remove Bonzo from the previous example’s ender.js file). The new ender.js file will contain the selector engine goodness from Qwery, and event management from Bean, but not much else.

Bonzo can be loaded separately, but we’ll need some special glue to do this. In Ender parlance, this glue is called an Ender Bridge.

The Ender Bridge

Ender follows the basic CommonJS Module pattern – it sets up a simple module registry and gives each module a module.exports object and a require() method that can be used to fetch any other modules in the build. It also uses a provide('name', module.exports) method to insert exports into the registry with the name of your module. The exact details here aren’t important and I’ll cover how you can build your own Ender module in a later article, for now we just need a basic understanding of the module registry system.

Using our Qwery, Bean and Bonzo build, the file looks something like this:

|========================================|
| Ender initialisation & module registry |
| (we call this the 'client library')    |
|========================================|
| 'module.exports' setup                 |
|----------------------------------------|
| Qwery source                           |
|----------------------------------------|
| provide('qwery', module.exports)       |
|----------------------------------------|
| Qwery bridge                           |
==========================================
| 'module.exports' setup                 |
|----------------------------------------|
| Bean source                            |
|----------------------------------------|
| provide('bean', module.exports)        |
|----------------------------------------|
| Bean bridge                            |
==========================================
| 'module.exports' setup                 |
|----------------------------------------|
| Bonzo source                           |
|----------------------------------------|
| provide('bonzo', module.exports)       |
|----------------------------------------|
| Bonzo bridge                           |
==========================================

To be a useful Ender library, the code should be able to adhere to the CommonJS Module pattern if a module.exports or exports object exists. Many libraries already do this so they can operate both in the browser and in a CommonJS environment such as Node. Consider Underscore.js for example, it detects the existence of exports and inserts itself onto that object if it exists, otherwise it inserts itself into the global (i.e. window) object. This is how Ender compatible libraries that can also be used as stand-alone libraries work too.

So, skipping over the complexities here, our libraries are registered within Ender and then we encounter the Bridge. Technically the bridge is just an arbitrary piece of code that Ender-compatible libraries are allowed to provide the Ender CLI tool; it could be anything. The intention, though, is to use it as a glue to bind the library into the core ender / $ object. A bridge isn’t necessary and can be omitted – in this case everything found on module.exports is automatically bound to the ender / $ object. Underscore.js doesn’t need a bridge because it conforms to the standard CommonJS pattern and its methods are utilities that logically belong on $ – for example, $.each(list, callback). If a module needs to operate on $('selector') collections then it needs a special binding for its methods. Many modules also require quite complex bindings to make them work nicely inside the Ender environment.

Bonzo has one of the most complex bridges that you’ll find in the Endersphere, so we won’t be looking into it here. If you’re interested in digging deeper, a simpler bridge with some interesting features can be found in Morpheus, an animation framework for Ender. Morpheus adds a $.tween() method and also an $('selector').animate() and some additional helper methods.

The simplest form of Ender bridge is one that lifts the module.exports methods to a new namespace. Consider Moment.js, the popular date and time library. When used in a CommonJS environment it adds all of its methods to module.exports. Without a bridge, when added to an Ender build you’d end up with $.utc(), $.unix(), $.add(), $.subtract() and other methods that don’t have very meaningful names outside of Moment.js. They are also likely to conflict with other libraries that you may want to add to your Ender build. The logical solution is to lift them up to $.moment.utc() etc., then you also get to use the exported main function as $.moment(Date|String|Number). To achieve this, Moment.js’ bridge looks like this:

$.ender({ moment: require('moment') })

The $.ender() method is the way that a bridge can add methods to the global ender / $ object, it takes an optional boolean argument to indicate whether the methods can operate on DOM element collections, i.e. $('selector').method().

Bonzo in Parts

Back to what we were originally trying to achieve: we’re loading Bonzo as a stand-alone library and we want to integrate it into an Ender build in the browser. There are two important things we need to do to achieve this: (1) load Bonzo’s bridge so it can wire Bonzo into Ender, and (2) make Ender aware of Bonzo so a require('bonzo') will do the right thing because this is how the bridge fetches Bonzo.

Let’s first do this the easy way. With an Ender build that just contains Qwery and Bean and Bonzo’s bridge in a separate file named bonzo-ender-bridge.js, we can do the following:

<!-- the order of the first two doesn't matter -->
<script src="ender.js"></script>
<script src="bonzo.js"></script>
<script>
  provide('bonzo', bonzo)
</script>
<script src="bonzo-ender-bridge.js"></script>

If you look at the diagram of the Ender file structure above you’ll see that we’re replicating it with our <script> tags but replacing provide('bonzo', module.exports) with provide('bonzo', bonzo) as Bonzo has detected that it’s not operating inside of a CommonJS environment with module.exports available. Instead, it’s attached itself to the global (window) object. Both provide() and require() are available on the global object and can be used outside of Ender (for example, to extract Bean out of an integrated build you could simply var bean = require('bean').)

We can now continue to use exactly the same script as in our fully integrated Ender build example:

$('<pre>')
  .text($('#scr').text())
  .css({
    fontWeight: 'bold',
    border: 'solid 1px red',
    margin: 10,
    padding: 10
  })
  .bind('click', function () {
    alert('Clickety clack');
  })
  .appendTo('body');

You can run this as example3, also available in my GitHub repository for this article.

Reducing <script> Tags

The main problem with the last example is that we have three <script> tags in our page with files loading (synchronously) from our server. We can trim that down to just two, and if bonzo.js is already cached in the browser then it’ll just be loading one script.

We could achieve this by hacking our ender.js file to include the needed code, or, we could create our own Ender package that contains our code so they will persist even after the Ender CLI tool has touched the file.

First we make a new directory to contain our package. We’ll include the Bonzo bridge as a separate file and also create a file for our provide() statement. Finally, a basic package.json file points to our provide() file as the source (“main”) of the package and the Bonzo bridge as our bridge (“ender”) file:

{
  "name": "fake-bonzo",
  "version": "0.0.0",
  "description": "Fake Bonzo",
  "main": "main.js",
  "ender": "bonzo-ender-bridge.js"
}

We then point the Ender CLI to this directory: ender build qwery bean ./fake-bonzo/ (or we could run ender add ./fake-bonzo/ to add it to the ender.js created in the above example).

The completed page now looks like this:

<!DOCTYPE HTML>
<html lang="en-us">
<head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <title>Example 4</title>
</head>
<body>
  <script src="bonzo.js"></script>
  <script src="ender.js"></script>
  <script id="scr">
    $('<pre>')
      .text($('#scr').text())
      .css({
        fontWeight: 'bold',
        border: 'solid 1px red',
        margin: 10,
        padding: 10
      })
      .bind('click', function () {
        alert('Clickety clack');
      })
      .appendTo('body');

  </script>
</body>
</html>

You can dig further into this and run it as example4, also available in my GitHub repository for this article.

Conclusion

Hopefully this has helped demystify the way that Ender packages libraries together; it’s really not magic. If you want to dig deeper then a good place to start would be to examine the client library that appears at the top of each Ender build—it’s relatively straightforward and fairly short.

Node Roundup: 0.8.7, Buffet, HARedis, Deployd

22 Aug 2012 | By Alex Young | Comments | Tags node modules frameworks WebSocket redis libraries
You can send in your Node projects for review through our contact form or @dailyjs.

Node 0.8.7

Node 0.8.7 is out, which includes fixes for SSL, TLS, buffer and crypto issues, and also a few Windows-specific problems. I noticed someone posted about an issue with the latest npm in Windows, but other than that 0.8.7 seems solid.

Buffet

Buffet (License: MIT, npm: buffet) by Carlos Rodriguez is a “performance-oriented” static file server:

Buffet takes a fully-bufferred approach – all files are fully loaded into memory when your app boots, so you will never feel the burn of the filesystem. In practice, this is immensely efficient. So much so that putting Varnish in front of your app might even make it slower!

It supports gzip, and will update files when they’re changed. The name of the index.html and 404.html files can be changed, and other configuration options include maxAge for setting the Cache-Control header.

The author has included Mocha tests and the project is on Travis CI.

HARedis

HARedis (License: MIT, npm: haredis) also by Carlos Rodriguez is a wrapper around node_redis that helps build fault-tolerant clusters of Redis servers. The main API difference is createClient, which accepts an array of hosts and ports, and this works with colon-separated strings for 'ip:port'.

Carlos has included the test suite from the original redis module, so running make test-cluster or make test can be used to test the project.

Deployd

Deployd (GitHub: deployd / deployd, License: Apache 2.0, npm: deployd) by Ritchie Martori and the Deployd team is a toolkit for building real-time APIs suited to web and mobile applications.

Deployd applications are created with a command-line tool called dpd. A newly created app includes a web IDE for managing the applications resources – this is basically a schema that Deployd will use to generate a suitable RESTful API. There’s a Deployd Hello World tutorial that covers the basics, and a Deployd screencast.

The project is built on technologies like Socket.IO and MongoDB, and includes tests written with Mocha.

jQuery Roundup: Infinity.js, lorem, oriDomi

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

Infinity.js

Infinity.js

Infinity.js (GitHub: airbnb / infinity, License: BSD) from developers at Airbnb is an infinite scrolling plugin based on the iOS UITableView class. It’s implemented by using containers that move content in and out of the DOM based on throttled scroll events, to keep scrolling smooth. The current version has some caveats – ListViews can’t be nested or have a height set by CSS.

To back up the performance claims, the authors have made demo pages with Infinity.js turned on and turned off. At least in my browser, it’s clear that Infinity.js improves the performance. Also, several performance enhancements are currently planned, including changing the internal ListItem array to use a self-balancing binary tree.

lorem

lorem (License: MIT, npm: lorem) by Stanley Shyiko is a text generator that works with Node and browsers, and it includes optional jQuery plugin support:

$(selector).ipsum();

The author has included Nodeunit tests, and a build script.

oriDomi

oriDomi (GitHub: dmotz / oriDomi, License: MIT) by Dan Motzenbecker is a small script with optional jQuery support that creates an effect on images and web fonts that looks like folding paper, by using CSS 3D transforms.

$(selector).oriDomi({
  vPanels: 3
, hPanels: 10
, perspective: 200
, speed: 500
, shading: false
});

It works best when it can figure out the dimensions of the element it’s applied to, so it’s probably a good idea to ensure images used with the effect have width and height attributes.

JS101: The Language Past and Present

20 Aug 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner

We’ve covered a lot of ground since the first JS101, but the truth is I’ve missed out an important question: what is JavaScript, and who controls it?

I’ve answered this question and covered a lot more in the History of JavaScript series. This post is a brief introduction, and after reading this post you should know the basics of JavaScript and its relationship to ECMAScript.

Who Made JavaScript?

JavaScript was created by Brendan Eich in 1995 for Netscape. Netscape submitted JavaScript to Ecma International, which is a standards organization based in Geneva. The standardised version is known as ECMAScript.

What is ECMAScript?

Most articles on sites like DailyJS will refer to ECMA-262, ECMAScript 3, and ECMAScript 5. We usually abbreviate these terms to ES3 and ES5.

  • ECMA-262 is the name of the specification, of which there are five editions
  • ECMAScript 3 (or ECMA-262, edition 3) was published in December 1999, and was supported by Netscape 6 and IE 5.5
  • ECMAScript 5 (or ECMA-262, edition 5) was published in December 2009 and is supported by Firefox 4+, Safari 6: ES5 compatibility table

ECMAScript 5 adds a lot of features that we’ve already started to take for granted: including new array methods like forEach, new Object methods like Object.create, property attributes, function binding, and more.

The Future

ECMAScript is still being actively developed. It’s tentatively known as ES.next (ECMA-262 Edition 6), and ES.next working drafts can be downloaded from the ECMAScript wiki.

Proposals for the language are collected on the strawman wiki, and discussed in detail by several contributors on the wiki and mailing lists. To keep up with this, I often check the wiki’s recent changes and the es-discuss mailing list.

Brendan Eich’s blog covers a lot of the major developments as well. For example, his latest post mentions ES6 and the relationship between the standards makers and the enthusiastic JavaScript developer community.

The language will change, and as new standards are made available you’ll need to know what your given platform or browser supports.

App.net Node Module, Prototype 1.7.1, Self, Qwerty Hancock, MilkChart

17 Aug 2012 | By Alex Young | Comments | Tags libraries node browser audio social prototype graphs

App.net Node Module

There’s already an App.net Node module: damienklinnert / appdotnet (License: MIT, npm: appdotnet. Created by Damien Klinnert, it uses the popular request HTTP module, and has Mocha tests. It supports authentication, users, and posts.

Creating a post is very simple:

client.createPost(config.post_data, function(err, post) {
  // Do something with `post`
});

Prototype 1.7.1

(SFX: Simple Minds - Alive And Kicking)

Prototype 1.7.1 has been released, which includes a rewrite of the DOM code, ECMAScript 5 compatibility, as well as other bug fixes.

Many of you have wondered whether Prototype is “dead,” and I can say that it definitely isn’t. But because of the way I work on Prototype - months of inaction followed by a flurry of commits and bug fixes - it’s fair to say that Prototype hibernates for long periods of time.

Self

Self (License: MIT, npm: self) by Ryan Munro is a class library based on Python. It supports inheritance, mixins, static properties, and can work with plain old prototype classes and Backbone.

Self is class-based sugar that’s perfect for continuation-passing style. No more var that = this;! The implicit this variable is changed to an explicit self variable that your inner functions inherit. Self plays nicely with existing prototypal, and Backbone OOP.

Self can be used with browsers and in Node programs, and includes tests for both environments.

Qwerty Hancock

Query Hancock

Qwerty Hancock (GitHub: stuartmemo / qwerty-hancock, License: MIT) by Stuart Memo is a “vector qwerty keyboard”. The project’s site demonstrates the keyboard by hooking it up to some Audio API code, so it’s actually a reusable keyboard widget that could be used to build other music-related projects.

MilkChart

MilkChart (License: MIT) by Brett Dixon is a graph library for MooTools. It generates graphs that look like Excel. It’s designed to transform HTML tables into charts, so it’s easy to integrate it with existing markup that requires graphs.

Backbone.js: Internals Summary

16 Aug 2012 | By Alex Young | Comments | Tags mvc tutorials backbone.js code-review

Over the last month we’ve looked at Backbone’s internals in detail. This post summarises these findings.

To recap, here’s a list of all the parts in Backbone.js: Hacker’s Guide:

  • Part 1: Setup, Events, Models
  • Part 2: Constructor, Inheritance, Collections, Chainable API
  • Part 3: Router, History, Views
  • Part 4: Inheritance, Sync

Leverage Events

Backbone’s classes are designed to be inherited from. Every single one of these classes inherits from Backbone.Events:

  • Backbone.Model
  • Backbone.Collection
  • Backbone.Router
  • Backbone.History
  • Backbone.View

That means when designing applications built with Backbone, events are a key architectural component. Events are the standard way to deal with user interface actions, through the declarative event bindings on views, and also model and collection changes. However, you can easily add your own custom events.

When learning Backbone it’s important to get a feel for the built-in event names. Incorrectly binding a collection reset event, for example, could cause your application to render more often than it should. Mastering events is one of the quickest ways to become more productive with Backbone.

Underscore.js

Since Backbone depends on Underscore, it’s worth keeping this in mind when dealing with any kind of arrays or collections of data. Also, familiarity with Underscore’s methods will help work with Backbone.Collection effectively.

Views

It’s easy to slip into using $, but avoid this where possible. Backbone caches a view’s element, so use this.$el instead. Design views based on the single responsibility principle.

It might be tempting to let “container” view render HTML directly by using $().html, but resisting the temptation and creating a hierarchy of views will make it much easier to debug your code and write automated tests.

Interestingly, Backbone doesn’t have a lot of code dedicated to templates, but it can work with the template method. I use this with RequireJS text file dependencies to load remote templates during development, then I use the RequireJS build script to generate something suitable for deployment. This makes code easy to test and fast to load.

API Style

Backbone’s API is thankfully very consistent. Even the history API accepts a silent option, which is used throughout the library to stop events from firing when they’re not required.

Backbone’s collections have Underscore’s chainable API, which can be handy, but care must be taken to use this correctly.

Testing Backbone

So far I’ve been reviewing Backbone’s code to demystify the framework as a whole. However, it’s worth noting that other technologies work very well with Backbone and Underscore. RequireJS and AMD modules can be a great way to break up projects.

However, one area that Backbone doesn’t address is testing. This is unfortunate, because testing Backbone projects definitely isn’t obvious. In Unit Testing Backbone.js Apps With QUnit And SinonJS, Addy Osmani describes one method in detail.

I have the following rules for testing Backbone projects:

  1. The full application should be running during testing
  2. Tests shouldn’t depend on any markup in the test harness HTML file (or as little as possible)
  3. Tests shouldn’t touch the network for data

The second rule in particular is aided by using templates loaded by RequireJS and avoiding those pesky calls to $() in views.

Node Roundup: Surviving npm Downtime, Waf Wall of Shame, stream-chat, Vein

15 Aug 2012 | By Alex Young | Comments | Tags node modules RPC WebSocket npm templating
You can send in your Node projects for review through our contact form or @dailyjs.

Surviving npm Downtime

On Sunday morning (UTC) part of npm’s service stopped functioning correctly, which meant the command-line tool failed to download packages. In response to this, Dominique Sandoz stepped up and created a mirror. Mirrors can be used by changing the location of the npm registry:

npm set registry http://npm.example.com
npm set registry https://registry.npmjs.org

Fortunately npm is now working correctly, but to help prepare for future downtime I recommend bookmarking this gist that Dominique wrote containing a list of npm mirrors and proxies.

During the downtime, several other users also offered their own solutions, mostly collaborating on Twitter and IRC. For example, Maciej Małecki created a proxy-based solution.

To my knowledge there has been no official statement on the service outage, and additionally there is no official Node/npm service status page. Hopefully someone will write up details about the outage on blog.nodejs.org, and outline the preventative measures taken to ensure future stability.

Node-waf Wall of Shame

Isaac Schlueter posted a Tweet referencing what he calls the “Node-waf wall of shame”:

Node-waf wall of shame: http://j.mp/node-waf-users Upgrade your packages to node-gyp. http://npm.im/node-gyp #deathtowaf

As I mentioned in the Windows and Node series, it’s time to move addons over to node-gyp.

stream-chat

stream-chat (License: MIT) by Raynos is a chat app based around streams. It uses the boot and multi-channel-mdm modules by the same author to route streams between browsers and Node servers.

An added bonus is the author has designed the chat app to be scalable by using seaport and mountie by James Halliday. Seaport helps manage clusters of servers, while mountie allows applications to be composed of smaller servers behind mount points. Routing is handled by bouncy. These modules help design larger systems according to the concept of separation of concerns, which suits Node web applications.

MinnaHTML.js

MinnaHTML.js (License: GPL v3, npm: minnahtml) by Robee Shepherd is an async-friendly HTML object library that can be used to build HTML:

var mh = require('minnahtml').mh
  , html = new mh.Html()
  , head = new mh.Head(html)
  ;

 new mh.Title(head).data.content = 'Example';
 
 console.log(html.generateHtml());

// <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
// <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
//  <head>
//   <title>
//    Example
//   </title>
//  </head>
// </html>

The author has provided a walkthrough that covers more features in the project’s readme file.

Vein

Vein (License: MIT, npm: vein) is a WebSocket RPC module. It includes both client and server code, and a minimised build for browsers. RPC methods can be added using vein.add, and then called from clients:

// Server
vein.add('multiply', function(res, numOne, numTwo) {
  res.reply(numOne * numTwo);
});

// Browser
var vein = Vein.createClient();
vein.on('ready', function(services) {
  vein.multiply(2, 5, function(num) {
    // num === 10
  });
});

jQuery Roundup: jQuery 1.8, BBSearch, MDMagick, Document-Bootstrap, DownloadBuilder.js

14 Aug 2012 | By Alex Young | Comments | Tags jquery plugins backbone.js sessionStorage files
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

jQuery 1.8

jQuery 1.8 has been released. jQuery 1.8 makes some fairly significant changes:

  • The selector engine has been rewritten
  • Animations have been reworked
  • .css and .animate will automatically add vendor prefixes
  • The size has been reduced compared to jQuery 1.7.2
  • Grunt build system

BBSearch

BBSearch (GitHub: fguillen / BBSearch, License: CC BY 3.0) by Fernando Guillen is a find-as-you-type style plugin that’s designed to work with Backbone.js. It can also work with JSONP APIs, and the author has included demos that use GitHub and Twitter.

$('#search-input-1').bbsearch({
  url: 'https://api.github.com/legacy/repos/search/#bbsearch-query#?callback=?&'
, itemTemplate: '<p>[@<%= owner %>] <a href="<%= url %>"><%= name %></a></p>'
, resultsElement: $('#results-1')
, parse: function(response) { return response.data.repositories; }
});

MDMagick

MDMagick

MDMagick (GitHub: fguillen / MDMagick, License: CC BY 3.0) also by Fernando Guillen is a Markdown interface for jQuery. It uses Showdown, which is a Markdown parser for JavaScript, and a-tools for handling text selections.

Document-Bootstrap and DownloadBuilder.js

Document-Bootstrap (GitHub: gfranko / Document-Bootstrap, License: MIT) by Greg Franko is a boilerplate for creating responsive Bootstrap projects. It also includes DownloadBuilder.js (GitHub: gfranko / DownloadBuilder.js, License: MIT), a project by the same author that uses the HTML5 File API to create optimised client-side scripts.

DownloadBuilder.js supports concatenating local files and files hosted on GitHub. It can also cache Ajax/JSONP requests by using sessionStorage.

DailyJS is Looking for Writers

13 Aug 2012 | By Alex Young | Comments | Tags community news

Over the last three years I’ve written over 700 articles for DailyJS. I’ve written through national holidays, trips to Europe and Asia, and I’ve enjoyed every minute of it! The time has come, however, to look for more writers. In September I’m going to become a father, and naturally family obligations will take priority for a few weeks.

Rather than leave readers without their daily dose of JavaScript news and tutorials, I’m looking for writers to contribute to the site. If you’re an open source developer and would like to promote your latest Node module or client-side library by writing a tutorial: this is your chance! I’m also interested in hearing from developers of commercial services that are relevant to JavaScript developers.

Before writing anything, fill out this form to get in touch. I’ll let you know if your suggestion is appropriate for the site.

Writing Guide

  • Articles do not need to be long – three to five paragraphs is great, otherwise consider writing a series of articles
  • Markdown is fine, although we use weird tags for code samples – here is an example post
  • British or American English is acceptable
  • DailyJS reserves the right to edit your article before publishing it

Payment

Articles will be paid for at a base rate of $25. Payment terms are negotiable, and may be subject to exchange rate conversion.

Submit your article idea here.

HubSearch, canvas-charts, Motown

10 Aug 2012 | By Alex Young | Comments | Tags libraries browser ui windows apps metro

HubSearch

HubSearch

HubSearch (GitHub: jgallen23 / hubsearch) by Greg Allen is a GitHub search interface built with Bootstrap, Underscore, and his own Fidel library for Backbone-style controllers.

I spend a lot of time searching GitHub to find projects to write about, so it’s good to see a tool that tries to improve on GitHub’s inadequate search interface.

canvas-charts

canvas-charts (License: MIT) by Praneet Loke is a graph library that only relies on the HTML5 Canvas API. The library includes a method to check if the Canvas element is supported, and it accepts an object containing options:

var chartingCanvas = new CanvasCharts();
if (chartingCanvas.isCanvasSupported()) {
  chartingCanvas.configure{
    gradientColor1: '#cd9603'
  , gradientColor2: '#f1de3f' // etc.
  });

  chartingCanvas.createCanvas($('graph'), width, height);
  // Given suitable arrays of labels for the x and y axes
  chartingCanvas.drawChart(xaxis, 90, yaxis, 35, [10, 20, 30 20, 10]);
}

Motown

Motown (GitHub: mtilchen / motown, License: LGPL v3) by Matthew P. Tilchen is a library for creating Metro-style Windows 8 applications using HTML, CSS, and JavaScript. Matthew sent this in before Microsoft decided to change the Metro name, but at this point everyone interested in this project should understand the name’s origin.

The WinJS libraries and bindings to WinRT provide a solid foundation for building applications but I feel that a significant gap remains. Microsoft […] intentionally left […] this for the development community to fill. I created the Motown JavaScript library […] to fill the gap.

This library is based on Microsoft’s JavaScript Windows API, and is built according to Microsoft’s recommendations:

Microsoft recommends that developers use a “single-page” style of navigation instead of a “multi-page” style in their applications.

Motown also supports navigation transition animations, application life cycle methods, and a declarative approach to binding HTML views to JavaScript. The project includes a Visual Studio 2012 plugin for creating new Motown apps.

Backbone.js: Hacker's Guide Part 4

09 Aug 2012 | By Alex Young | Comments | Tags mvc tutorials backbone.js code-review

Last week we looked at Backbone’s History and View APIs. We’re coming to the end of this detailed look at Backbone’s internals, but there are still a few interesting things left:

  • Backbone’s inheritance implementation
  • Backbone.sync

Backbone’s inheritance Implementation

The comments indicate that the inherits function is inspired by goog.inherits. Google’s implementation is from the Closure Library, but Backbone’s API accepts two objects (incorrectly referred to as a hash) containing “instance” and “static” methods. Each of Backbone’s objects has an extend method:

Model.extend = Collection.extend = Router.extend = View.extend = extend;

Most development with Backbone is based around inheriting from these objects, and they’re designed to mimic a classical object-oriented implementation.

Backbone uses Underscore’s extend method:

each(slice.call(arguments, 1), function(source) {
  for (var prop in source) {
    obj[prop] = source[prop];
  }
});
return obj;

This isn’t the same as ES5’s Object.create, it’s actually copying properties (methods and values) from one object to another. Since this isn’t enough to support Backbone’s inheritance and class model, the following steps are performed:

  1. The instance methods are checked to see if there’s a constructor property. If so, the class’s constructor is used, otherwise the parent’s constructor is used (i.e., Backbone.Model)
  2. Underscore’s extend method is called to add the parent class’s methods to the new child class
  3. The prototype property of a blank constructor function is assigned with the parent’s prototype, and a new instance of this is set to the child’s prototype property
  4. Underscore’s extend method is called twice to add the static and instance methods to the child class
  5. The child’s prototype’s constructor and a __super__ property are assigned

This pattern is also used for classes in CoffeeScript, so Backbone classes are compatible with CoffeeScript classes.

Update: Jeremy Ashkenas clarified this process on Twitter:

… it’s just your basic prototype chain, plus one extra goodie: any constructor properties (static) are copied over as well.

Backbone’s Sync API

The Backbone.sync method is intended to be overridden to support other backends. The built-in method is tailed to a certain breed of RESTful JSON APIs – Backbone was originally extracted from a Ruby on Rails application, which uses HTTP methods like PUT the same way.

The way this works is the model and collection classes have a sync method that calls Backbone.sync. Both will call this.sync internally when fetching, saving, or deleting items.

The sync method is called with three parameters:

  • method: One of create, update, delete, read
  • model: The Backbone model object
  • options: May include success and error methods

Implementing a new sync method can use the following pattern:

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

  function success(result) {
    // Handle results from MyAPI
    if (options.success) {
      options.success(result);
    }
  }

  function error(result) {
    // Handle results from MyAPI
    if (options.error) {
      options.error(result);
    }
  }

  options || (options = {});

  switch (method) {
    case 'create':
      requestContent['resource'] = model.toJSON();
      return MyAPI.create(model, success, error);

    case 'update':
      requestContent['resource'] = model.toJSON();
      return MyAPI.update(model, success, error);

    case 'delete':
      return MyAPI.destroy(model, success, error);

    case 'read':
      if (model.attributes[model.idAttribute]) {
        return MyAPI.find(model, success, error);
      } else {
        return MyAPI.findAll(model, success, error);
      }
  }
};

This pattern delegates API calls to a new object, which could be a Backbone-style class that supports events. This can be safely tested separately, and potentially used with libraries other than Backbone.

There are quite a few sync implementations out there:

Node Roundup: Node 0.8.6, Axon, NextFlow

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

Node 0.8.6

Node 0.8.6 is out, and this release is the first to include binary distributions for all supported Unix systems.

The 0.6 series has also been updated, with the release of 0.6.21. This release fixes a bug in fs.watch that affected Solaris.

Axon

Axon (License: MIT, npm: axon) by TJ Holowaychuk is a zeromq-inspired message-oriented socket library. It uses the push/pull and publish/subscribe patterns, and features a lightweight wire protocol that supports binary messages.

Axon is JavaScript, so it might work well in situations where a messaging system is desired but additional software installation is not. The API is friendly for Node developers, particularly the EmitterSocket object which behaves like Node’s EventEmitter.

TJ has included information on the protocol and some rough benchmarks.

NextFlow

NextFlow (License: MIT, npm: nextflow) by JP Richardson is a control flow library for Node that has a CoffeeScript-friendly API. Rather than using a chainable API or a list of arguments, NextFlow accepts an object:

next = require('nextflow')

vals = []
x = 0

next flow =
  1: ->
    vals.push(1)
    @next()
  2: ->
    vals.push(2)
    x = Math.random()
    @next(x)
  3: (num) ->
    vals.push(num)
    @next()
  4: ->
    vals.push(4)
    @next()
  5: ->
    console.log vals[0] #is 1
    console.log vals[1] #is 2
    console.log vals[2] #is x
    console.log vals[3] #is 4

The author has included CoffeeScript comparisons with well-known Node control flow libraries.

jQuery Roundup: AutobahnJS, Grid Builder, Best Ampersand

07 Aug 2012 | By Alex Young | Comments | Tags jquery plugins libraries WebSocket ui
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

AutobahnJS

AutobahnJS (GitHub: tavendo / AutobahnJS, License: MIT) from Tavendo GmbH is a client library that implements the The WebSocket Application Messaging Protocol (WAMP). The API is asynchronous and promise-based, so it can use jQuery’s Deferred object or similar implementations. Publish/Subscribe and RPC are both supported by the library.

The RPC API looks like this:

// WAMP server
var wsuri = 'ws://localhost:9000';
ab.connect(wsuri,
  // WAMP session was established
  function(session) {
    // Asynchronous RPC, returns promise object
    session.call('http://example.com/simple/calc#add', 23, 7).then(
      // RPC success callback
      function(res) {
        console.log('got result:', res);
      },

      // RPC error callback
      function(error, desc) {
        console.log('error:', desc);
      }
    );
  },

  // WAMP session is gone
  function(code, reason) {
    console.log(reason);
  }
);

The authors have written tutorials for Publish/Subscribe with AutobahnJS and RPC.

jQuerin Grid Builder

jQuerin Grid Builder (GitHub: kanakiyajay / jQuerin-grid-builder, License: MIT/GPL) by Jay Kanakiya is an interactive tool that generates HTML and CSS for grid-based layouts.

Attributes like class and id can be added to cells, and multiple levels of rows and columns can be created once you get the hang of the interface.

Best Ampersand

Best Ampersand (GitHub: gmurphey / jQuery.Best-Ampersand, License: MIT/GPL) by Garrett Murphey is a simple plugin that wraps ampersands in spans so they can be styled with the best available ampersand. Garrett has written this plugin using a TDD approach, and he’s included unit tests and the build script.

He also sent in Outbound Analytics, which can help track outbound links with Google Analytics.

JS101: Enumeration

06 Aug 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner

In this article we’ll look at JavaScript’s enumeration capabilities. This is partly related to scope, so take a look at JS101: A Brief Lesson on Scope if you haven’t read it yet.

Correctly Using for-in

The for-in statement is intended to be used to enumerate over the properties of an object. Inherited properties are included, and to avoid iterating over them hasOwnProperty should be used.

This example demonstrates using for-in, and shows what happens when someone adds a property to a native prototype:

Object.prototype.bad = undefined;

var name, names;

names = {
  bill: { age: 44 }
, bob: { age: 22 }
, john: { age: 29 }
};

for (var name in names) {
  if (names.hasOwnProperty(name)) {
    console.log(name, names[name].age);
  } else {
    console.log('Inherited:', name);
  }
}

The output will show the inherited property that we don’t want. Even though the property has been set to undefined, it still exists and will be present when enumerated over. Some libraries may add properties this way (even though it’s generally considered bad practice), so it’s wise to use the following pattern:

for (var prop in exampleObject) {
  if (exampleObject.hasOwnProperty(prop)) {
    // Do stuff
  }
}

The Underscore.js library uses the same pattern in its implementation of _.each:

for (var key in obj) {
  if (_.has(obj, key)) {
    if (iterator.call(context, obj[key], key, obj) === breaker) return;
  }
}

Correctly Extending Objects

In ECMAScript 5, properties have an enumerable attribute. If this is set to fault, then the property won’t be included in a loop with for-in. There’s also a method called Object.prototype.propertyIsEnumerable, and methods like Object.keys will respect it.

If I really wanted to add a property to Object, then I could take advantage of this to correctly extend the built-in object:

Object.defineProperty(Object.prototype, 'bad', {
   value: undefined
 , enumerable: false // This property is not enumerable
});

var name, names;

names = {
  bill: { age: 44 }
, bob: { age: 22 }
, john: { age: 29 }
};

for (var name in names) {
  if (names.hasOwnProperty(name)) {
    console.log(name, names[name].age);
  } else {
    console.log('Inherited:', name);
  }
}

Running this example will leave out the bad property.

Notice that this doesn’t just apply to adding properties to native objects – you should also take enumerable into account when adding properties to your own objects.

ECMAScript 5 Array.prototype Methods

ECMAScript 5 introduces some handy methods to Array.prototype:

  • forEach(callback): Run callback over each element
  • filter(callback): Returns a new array for each item where callback returns true
  • map(callback): Run callback over each element, store the result, then return a new array containing the results
  • some(callback): If callback returns true, then stop iterating and return true

There are more methods, including indexOf, lastIndexOf, reduce, and reduceRight. These methods also take a thisArg parameter, which changes the value of this in the callback.

Remember that these are all methods on Array. To use them with an object, one approach is to call Object.keys. The previous example could be rewritten like this:

var name, names;

names = {
  bill: { age: 44 }
, bob: { age: 22 }
, john: { age: 29 }
};

Object.keys(names).forEach(function(name) {
  console.log(name);
});

Scope

In JS101: A Brief Lesson on Scope, I provided an example that showed how creating methods inside loops can cause confusing scope issues. Since forEach uses a callback, we now have a new scope for each iteration:

function example() {
  var o = {};

  [0, 1, 2, 3].forEach(function(i) {
    o[i] = function() { console.log(i); };
  });

  o[0]();
  o[1]();
  o[2]();
}

example();

This will correctly output 0 1 2 rather than the 3 3 3 that was printed with the for example.

Performance

If you’re working with an array of items, a simple for loop will still perform better than forEach:

var length = values.length, i;
for (i = 0; i < length; i++) {
  // Do something
}

There are dozens of benchmarks for this on jsPerf, but in general the good old fashioned for loop will beat forEach.

Relationship to Underscore.js

Underscore.js and jQuery both include methods that work like forEach. This makes it easier to write code that’ll work with older browsers.

Underscore works slightly different to forEach because it doesn’t extend Array.prototype, or any other built-in object. Instead, the array has to be passed as an argument:

_.forEach([0, 1, 2], function(i) {
  console.log(i);
});

The ECMAScript 5 forEach method will be used if it’s available, otherwise a for loop will be used instead.

rAppid:js, Portastic, jstesting

03 Aug 2012 | By Alex Young | Comments | Tags node browser libraries frameworks mvc testing

rAppid:js

rAppid:js (GitHub: it-ony / rAppid.js, License: MIT, npm: rAppid.js) by Tony Findeisen is a new client-side MVC framework that uses XAML for templates. The way the templates work reminds me of AngularJS, but rather than using custom attributes it uses XML documents.

Data can be bound between models and views, and can be set up to work bidirectionally. There’s also a Bindable class that can be used to allow any object to bind to views. Code is kept modular by using AMD and RequireJS. There’s also a Datasource class for calling RESTful data services.

The framework itself is tested with Mocha, but I can’t find anything that specifically addresses testing apps built with the framework. Also, I’m unsure of the relationship between the Node server that can run rAppid.js apps and generating “optimised” builds. The page that’s meant to show help on Node Rendering seems to redirect to the introduction to the project.

Portastic

Portastic (License: MIT, npm: portastic) by Alan Hoffmeister is a port scanner for Node. It’s actually very simple – it uses the async and built-in net modules to check for listening events for each port. It’s not exactly Nmap, so you won’t be using it to perform UDP, NULL, or Xmas scans. However, it is lightweight and includes tests written with Vows, so you could always see what else you can get it to do.

jstesting

jstesting by Bret Little is a project template for writing client-side tests. It includes Jasmine, RequireJS, jsTestDriver, and PhatomJS, and allows test to be run from a static HTML file or as a server.

This also supports headless testing through PhantomJS, so if you’re struggling to write tests for your latest client-side MVC project then this might help.

Backbone.js: Hacker's Guide Part 3

02 Aug 2012 | By Alex Young | Comments | Tags mvc tutorials backbone.js code-review

Last week we continued looking at Backbone.js’s internals, covering collections, and some interesting points about the chainable API design and its relationship to Underscore.js. Before continuing with this week’s post, here are some interesting articles that are in a similar vein to this series:

I’ve already mentioned the first on DailyJS, but I thought I’d mention it again in case you’re still feeling lost about what exactly MVC frameworks can do.

Meanwhile, I’m working on a tutorial series based on Backbone with a focus on combining it with a certain popular user interface component framework, and using a non-REST HTTP API. I’ll release the app itself within the next few weeks.

Router and History

The Backbone.Router constructor function is like the other Backbone classes, based around Underscore’s extend method. Routes are defined with the route method, and it will call _routeToRegExp if the route is a regular expression. This uses isRegExp, which is one of Underscore’s handy type checking methods.

You can use Underscore’s type checking methods in your own projects rather than reinventing them. For example, a lot of projects include a function to check if an argument is an array, but if you’ve already loaded Underscore then _.isArray can be used instead.

Most of what the router does is delegated to Backbone.History. These two classes work together – once a set of routes has been defined and instantiated, then Backbone.history.start must be called. Backbone is probably known for supporting hash URLs at this point, but it also supports the HTML5 History API.

The History class is where Backbone has to do a lot of work to get good cross-browser support, and this is particularly apparent in the start method:

this.options          = _.extend({}, {root: '/'}, this.options, options);
this._wantsHashChange = this.options.hashChange !== false;
this._wantsPushState  = !!this.options.pushState;
this._hasPushState    = !!(this.options.pushState && this.history && this.history.pushState);
var fragment          = this.getFragment();
var docMode           = document.documentMode;
var oldIE             = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));

if (oldIE && this._wantsHashChange) {
  this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
  this.navigate(fragment);
}

To use the History API, pushState: true must be supplied as an option, and the browser must support it. Otherwise, hash URLs will be used, or even iframes. Regardless, the checkUrl method will be called by listening to popstate, onhashchange, or by polling with setInterval.

Like other Backbone methods, start also accepts a silent option. Passing silent: true prevents loadUrl from being called when start is run. This is one of those small touches that shows just how consistent Backbone is.

The Backbone.Router class adds routes by calling Backbone.history.route. The Router class wraps the callback supplied by the user, and the History class adds it to an array of handlers. When the URL changes in the browser, the handlers array is searched, and if a match is found then the callback will run. Due to the way the callback is wrapped by Router, it actually triggers an event.

The beauty of this design is these events can be bound to elsewhere, and the navigate method which changes the current URL is a lot easier to implement:

app.navigate('help/troubleshooting', { trigger: true, replace: true });

This calls the router’s navigate method, which subsequently calls the one in History. URLs can either be replaced or added to the history array.

Views

Backbone.View is a relatively simple class that helps manage view fragments and events. It takes steps to ensure it has a valid DOM element to work with by calling _ensureElement, and includes methods for delegating DOM-related functionality to jQuery-like framework calls in the form of $ and make.

The most interesting part of this class is delegateEvents, which loops over the events property and applies the delegateEventSplitter regular expression to the event property’s keys. This is how Backbone turns things like 'click .button.edit': 'openEditDialog' into the usual jQuery syntax. This method is called by the constructor, and a lot of care is taken to correctly unbind events before adding or altering the view’s main element. You’ll see a few calls to undelegateEvents throughout the class to manage this.

Conclusion

I’ve written Backbone applications without using routers, so it’s interesting to take a deeper look at it and appreciate just how much effort has gone into making it cross-browser.

Although a lot of people see the Backbone.View class as a simple wrapper, it does handle correctly binding and unbinding events, and ensuring there are valid elements to work with.

Node Roundup: BinaryJS, Advice, Buildify, MaDGe

01 Aug 2012 | By Alex Young | Comments | Tags node modules graphics binary websockets
You can send in your Node projects for review through our contact form or @dailyjs.

BinaryJS

BinaryJS (GitHub: binaryjs / binaryjs, License: MIT, npm: binaryjs) by Eric Zhang uses WebSocket to stream binary data. The streams can be bidirectional, and is binary end-to-end. This basically gives browsers something closer to TCP sockets, and allows multimedia data to be streamed.

The client-side portion works with Chrome, Firefox, Internet Explorer 10, and Safari’s nightly builds. The authors are working on supporting older browsers (presumably through Flash).

BinaryJS employs BinaryPack a modified version of the MessagePack protocol. The Node.js server uses a modified version of the ws library enhanced to pass through the status of the socket buffer so adherence to Node.js Stream API is possible.

Advice Functional Mixin

Advice (License: MIT, npm: advice) by Martin Angers is inspired by Angus Croll’s functional mixin example. It can be used to modify an object with after, before, and around methods:

var myObj = { fn: function() {} }
  , withAdvice = require('advice');

withAdvice.call(myObj)
myObj.before(fn, function() {
  // Things that should happen before fn
});

// the 'before' method will now run automatically
myObj.fn();

The author has kindly included thorough Mocha tests as well.

Buildify

Buildify (License: MIT, npm: buildify) by Charles Davison is a build script API:

var buildify = require('buildify');

buildify()
  .load('base.js')
  .concat(['part1.js', 'part2.js'])
  .wrap('../lib/template.js', { version: '1.0' })
  .save('../distribution/output.js')
  .uglify()
  .save('../distribution/output.min.js');

MaDGe

MaDGe (License: MIT, npm: madge) by Patrik Henningsson generates graphs based on CommonJS or AMD dependencies. It can generate various output including text-based lists in the console, and PNGs using Graphviz. There are lots of commnad-line options, which can be loaded from a JSON file.

This example shows the result of using MaDGe with Express:

MaDGe/Express

jQuery Roundup: Flex, jquery-binddata, jquery.notification

31 Jul 2012 | By Alex Young | Comments | Tags jquery plugins ui databinding notifications
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

Flex

jQuery Flex

Flex (GitHub: jasonenglish / jquery-flex, License: MIT) by Jason English displays an animated grid with expanding panels.

The author has based the effect on a design originally implemented with Flash. He was compelled to write the plugin after he found a discussion on Stack Overflow that suggested creating the effect with JavaScript would be impossible.

jquery-binddata

jquery-binddata is a new plugin created by “jdavidw13” that helps bind form fields to simple JavaScript data models. If you’re used to working with MVC frameworks and want to carry across some of the related data binding techniques to a smaller jQuery project, then this plugin might do the trick.

The basic usage is to provide the plugin with an object to bind and a form element:

var data = { field: 'value' };
$('form').binddata(data);

QUnit tests have been included, and the plugin is currently only about 200 lines long.

jquery.notification

jquery.notification (License: MIT) by Mikhail Davydov is a wrapper around the WebKit Notifications API. I’ve seen quite a few of these plugins, but I don’t think I’ve actually seen them used effectively in the wild.

If you’re looking for such a thing, the plugin looks like this:

var notification = $.notification(options, function(isNotificationsAllowed) {
  if (isNotificationsAllowed) {
    notification.show();
  }
});

Rivets.js, BackboneMVC, Unitools, Moog Source

30 Jul 2012 | By Alex Young | Comments | Tags backbone.js mvc unicode library audio

Rivets.js

Rivets.js (GitHub: mikeric / rivets, License: MIT) by Michael Richards is a data binding library that can be used with frameworks like Backbone.js. It has an adapter option that can be set up to support event-based models. Data formatting is supported, so data types like monetary values or dates can be displayed consistently.

Data attributes are used to describe the data bindings in HTML templates. There are built-in bindings like data-html for innerHTML, but tag attributes are also supported, so to write modelInstance.url to an image’s src attribute data-src could be used.

Rivets.js embraces a pipe-inspired syntax for certain operations. For example, rendering a collection could automatically sort the results like this:

<ul data-html="model.tags | sort | tagList"></ul>

BackboneMVC

BackboneMVC (GitHub: chance-an / backbone-mvc, License: LGPL) by Changsi An adds a controller to Backbone. Controllers are singletons, which means the same instance will always be returned. I suspect this might fit well if you’re wrapping classes with AMD and loading them with RequireJS.

Methods on controllers can be executed by Backbone.Router, so it works very much like Rails (the author states the project is inspired by CakePHP). The beforeFilter and afterRender hooks are executed based on a jQuery Deferred object, but false can be returned as well.

Unitools

Unitools is a collection of Unicode web-related tools for creating all manner of useful and ludicrous text effects.

It includes the Twitter favourite upside down mapping (”sɾʎlıɐp ɯoɹɟ ollǝɥ”), Zalgo, and tools for escaping and working with raw Unicode values.

Moog Google Doodle Open Sourced

I noticed the Moog Google Doodle has been released under the Apache 2.0 license here: bob-moog-google-doodle (HN discussion). I was coincidentally recently working on some web audio stuff, so it’s useful to have something like this to refer to.

TiddlyWiki5, Backbone.Notifier, MVC Jungle

27 Jul 2012 | By Alex Young | Comments | Tags apps mvc backbone.js libraries

TiddlyWiki5

TiddlyWiki5 (GitHub: Jermolene / TiddlyWiki5, npm: tiddlywikigithub) by Jeremy Ruston is a reboot of the venerable TiddlyWiki. As reboots go I’d say this was more along the lines of Batman Begins than The Amazing Spider-Man. It can run entirely in a browser, or as a Node application.

TiddlyWiki is designed to fit around your brain, giving you a better way of managing data compared to traditional documents and emails. The fundamental idea is that information is more useful and reusable if we cut it up into the smallest semantically meaningful chunks.

The project is currently tentatively released as an alpha, and you can keep track of future updates on the TiddlyWikiDev Google Group and @TiddlyWiki on Twitter.

Backbone.Notifier

Backbone.Notifier (License: MIT, GitHub: ewebdev / backbone.notifier) by Eyal Weiss is a notification library designed to work with Backbone.js. Features include dialogs, modal display, and CSS3-based effects.

The Backbone.Notifier class works like the other Backbone classes:

var notifier = new Backbone.Notifier(options);
nofitier.notity('What did one snowman say to the other snowman?');

Instances of Backbone.Notifier can be chained, and the class is event-based, which means it’s quite easy to create wizards by chaining together multiple dialogs.

Journey Through The JavaScript MVC Jungle

Journey Through The JavaScript MVC Jungle is a detailed article by Addy Osmani that introduces MVC frameworks and his TodoMVC collection of demos. There are also some handy descriptions of when to use each framework:

Use KnockoutJS: I want something that will help me build simple Web applications and websites. I don’t expect there to be a great deal of code involved and so code organisation won’t be much of a concern.