Models with js-model

10 Mar 2010 | By Alex Young | Comments | Tags libraries functional

js-model by Ben Pickles is a client-side library for working with the model layer. It’s not simply a REST proxy, it supports features like data caching, validation, and models can be hooked up to the UI using events.

Validations look like this:

var Post = Model('post', {
  validate: function() {
    if (this.attr("title") != "Bar") {
      this.errors.add("title", "should be Bar")
    }
  }
})

var post = new Post()
post.attr("title", "Foo")

post.valid()                // => false
post.errors.size()          // => 1
post.errors.on("title")     // => ["should be Bar"]
post.errors.all()           // => { title: ["should be Bar"] }

post.attr("title", "Bar")

post.valid()                // => true

REST can be used to persist data, but you could technically add your own persistence layer:

var Project = Model("project", {
  persistence: Model.RestPersistence("/projects")
})

This project requires jQuery and Underscore.

jQuery Plugin Roundup 3: gameQuery, hotkeys, qTip

09 Mar 2010 | By Alex Young | Comments | Tags jquery plugins games

Welcome to the jQuery Plugin Roundup, episode 3. Remember you can send your plugins in for review through our contact form or @dailyjs.

gameQuery

gameQuery is a jQuery plugin that helps make game development easier in JavaScript. It’s so advanced that the news section on its site has a post from 25th December 2010: so cutting edge that it’s from the future!

This plugin offers support for animations and sound handling. There are various sprite-based methods for manipulating graphics. Sprites can be CSS sprites, and gameQuery’s API can be called to automatically animate them based on horizontal or vertical frame positions. A sprite might look like this:

It can also do collision detection:

# This method returns the list of elements colliding with the selected one, according to a filter:
$("#spaceship").collision(".missiles").each(function() {
  kill_spaceship();
  explode_missile(this);
});

js-hotkeys

js-hotkeys helps manage handlers for keyboard events. The API is very simple and clean:

$(document).bind('keydown', 'ctrl+c', fn);
$(document).unbind('keydown', 'ctrl+c', fn);

qTip

qTip is a tooltip plugin that can generate very clear and configurable tooltips. The site has lots of demos, including a nifty one that uses a third-party service to generate external site previews:

The documentation explains what HTML gets generated by the plugin so you can easily customise the CSS. The API is very simple too:

$('ul:last li.active').qtip({
   content: 'This is an active list element',
   show: 'mouseover',
   hide: 'mouseout'
})

JavaScript Library Dependencies

08 Mar 2010 | By Alex Young | Comments | Tags server nodejs narwhal

I’ve been thinking about strategies for hosting JavaScript apps. One core part of this is dependency management — it makes deployment as smooth as possible, and takes away a lot of maintenance pain. But what library dependency management options are there right now?

Require and Packages

The building block of dependency management is require. This is specified in CommonJS modules, and they have unit tests for implementors to use.

That’s not enough though. Production server-side applications need to be specific about library versions to ensure that what’s deployed is tested and safe. Yet nobody wants to waste time downloading specific versions of scripts. This is where a package manager comes in handy.

Much like there are multiple implementations of JavaScript there can be many package managers. Some programming languages opt to bundle one as standard, and others allow the community to provide and support them.

Narwhal

Narwhal has tusk, which manages virtual environments and is also a package manager. Packages use a json file to express metadata like dependencies, and can include jars, executables, C and Java source, and engines.

The package.json files look like this:

{
    "author": "Author Name",
    "contributors": [
        "Contributor Name"
    ],
    "dependencies": [
        "narwhal"
    ],
    "jars": [
        "jars/simple-4.1.10.jar"
    ],
    "version": "0.2.2"
}

Tusk usage looks like this:

alex@mog ~/narwhal[git:master]$ tusk install jack
Updating catalog.
Downloading http://github.com/280north/narwhal/raw/master/catalog-2.json
# ... etc

Tusk installs into your own path, rather than system-wide. You could use it to manage your own apps to ease deployment to production servers.

Kiwi

Kiwi is a package manager for node.js. You can install it like this:

git clone git://github.com/visionmedia/kiwi.git
cd kiwi
# sudo if required or available
sudo make install
# This installs into ~/.kiwi
kiwi -v install oo

A node app that uses kiwi looks like this:

var kiwi = require('kiwi'),
    sys = require('sys')

sys.p(kiwi.require('oo'))

Kiwi uses YAML seed files:

---
  name: OO
  description: Object-Oriented Class support
  version: 1.2.0

Kiwi has an interactive shell where you can search and install packages. Packages are fetched from a remote server, where users can register and publish their own packages. It seems like it’s still early days for Kiwi, but it’s a promising start.

I tested kiwi with the current version of node from GitHub (3947270).

Node Blog and How To Node

05 Mar 2010 | By Alex Young | Comments | Tags nodejs software blgos

Node Blog is a static site generator which you can use to create a blog. It currently uses haml and markdown for templates and content.

Node Blog powers How To Node, which features some interesting articles about using node by Tim Caswell (creationix). You can get the source for How To Node in github.com/creationix/howtonode.org.

I’ve been slowly reading through all the How To Node articles, and I really enjoyed Node + Redis = Fun. It brings together some interesting libraries, like Nerve (a node microframework).

Let's Make a Framework: Classes, Inheritance, Extend

04 Mar 2010 | By Alex Young | Comments | Tags web frameworks tutorials lmaf

Not all JavaScript frameworks provide classes. Douglas Crockford discusses the classical object model in Classical Inheritance in JavaScript. It’s an excellent discussion of ways to implement inheritance in JavaScript. Later, he wrote Prototypal Inheritance in JavaScript in which he basically concludes prototypal inheritance is a strong enough approach without the classical object model.

So why do JavaScript libraries provide tools for OO programming? The reasons vary depending on the author. Some people like to ape an object model from their favourite language. Prototype is heavily Ruby inspired, and provides Class which can be useful for organising your own code. In fact, Prototype uses Class internally.

In this article I’m going to explain prototypal inheritance and OO, and start to create a class for OO in JavaScript. This will be used by our framework, turing.js.

Objects and Classes vs. Prototype Classes

Objects are… everything, so some languages attempt to treat everything as an object. That means a number is an object, a string is an object, a class definition is an object, an instantiated class is an object. The distinction between classes an objects is interesting — these languages treat classes as objects, and use a more basic object model to implement classes. Remember: it’s object oriented programming not class oriented.

So does that mean JavaScript really needs classical classes? If you’re a Java or Ruby programmer you might be surprised to find JavaScript doesn’t have a class keyword. That’s OK though! We can build our own features if we need them.

Prototype Classes

Prototype classes look like this:

function Vector(x, y) {
  this.x = x;
  this.y = y;
}

Vector.prototype.toString = function() {
  return 'x: ' + this.x + ', y: ' + this.y;
}

v = new Vector(1, 2);
// x: 1, y: 2 

If you’re not used to JavaScript’s object model, the first few lines might look strange. I’ve defined a function called Vector, then said new Vector(). The reason this works is that new creates a new object and then runs the function Vector, with this set to the new object.

The prototype property is where you define instance methods. This approach means that if you instantiate a vector, then add new methods to the prototype property, the old vectors will get the new methods. Isn’t that amazing?

Vector.prototype.add = function(vector) {
  this.x += vector.x;
  this.y += vector.y;
  return this;
}

v.add(new Vector(5, 5));
// x: 6, y: 7

Prototypal Inheritance

There’s no formal way of implementing inheritance in JavaScript. If we wanted to make a Point class by inheriting from Vector, it could look like this:

function Point(x, y, colour) {
  Vector.apply(this, arguments);
  this.colour = colour;
}

Point.prototype = new Vector;
Point.prototype.constructor = Point;

p = new Point(1, 2, 'red');
p.colour;
// red
p.x;
// 1

By using apply, Point can call Vector‘s constructor. You might be wondering where prototype.constructor comes from. This is a property that allows you to specify the function that creates the object’s prototype.

When creating your own objects, you also get some methods for free that descend from Object. Examples of these include toString and hasOwnProperty:

p.hasOwnProperty('colour');
// true

Prototypal vs. Classical

There are multiple patterns for handling prototypal inheritance. For this reason it’s useful to abstract it, and offer extra features beyond what JavaScript has as standard. Defining an API for classes keeps code simpler and makes it easer for people to navigate your code.

The fact that JavaScript’s object model splits up portions of a class can be visually noisy. It might be attractive to wrap entire classes up in a definite start and end. Since this is a teaching framework, wrapping up classes in discrete and readable chunks might be beneficial.

A Class Model Implementation Design

The previous example in Prototype looks like this:

Vector = Class.create({
  initialize: function(x, y) {
    this.x = x;
    this.y = y;
  },

  toString: function() {
    return 'x: ' + this.x + ', y: ' + this.y;
  }
});

Point = Class.create(Vector, {
  initialize: function($super, x, y, colour) {
    $super(x, y);
    this.colour = colour;
  }
});

Let’s create a simplified version of this that we can extend in the future. We’ll need the following:

  1. The ability to extend classes with new methods by copying them
  2. Class creation: use of apply and prototype.constructor to run the constructors
  3. The ability to determine if a parent class is being passed for inheritance
  4. Mixins

Extend

You’ll find extend littered through Prototype. All it does is copies methods from one prototype to another. This is a good way to really see how prototypes can be manipulated — it’s as simple as you think it is.

The essence of extend is this:

for (var property in source)
  destination[property] = source[property];

Class Creation

A create method will be used to create new classes. It will need to handle some setup to make inheritance possible, much like the examples above.

// This would be defined in our "oo" namespace
create: function(methods) {
  var klass = function() { this.initialize.apply(this, arguments); };

  // Copy the passed in methods
  extend(klass.prototype, methods);

  // Set the constructor
  klass.prototype.constructor = klass;

  // If there's no initialize method, set an empty one
  if (!klass.prototype.initialize)
    klass.prototype.initialize = function(){};

  return klass;
}

Get the Code

I’ve already created a basic OO class for turing in turing.oo.js. You can read it and experiment with it now.

I’ll continue this part next Thursday!

Notes on Teaching JavaScript

03 Mar 2010 | By Alex Young | Comments | Tags learning tutorials

Notes on Teaching JavaScript by Ian McCracken is a thoughtful post about the author’s experiences teaching JavaScript to a web designer. It made me realise how useful our Let’s Make a Framework series of posts could be.

McCracken says:

Nothing, however, teaches you JavaScript quite so well as rolling your own cross-browser Ajax utilities, and so I studied the source code of Prototype and script.aculo.us and MochiKit, and now I’m a far better programmer than someone starting out today might be forced to become.

I’ve found the same thing in the past. If you’ve ever worked on a project where you can’t use a popular framework, you suddenly have to learn a lot very quickly. Browser differences are a headache, which is why I’m glad these frameworks exist. What really shapes these libraries is JavaScript itself.

Creating a simple library turned out to be a fantastic learning exercise: it requires investigation of namespaces, presents plenty of scoping problems to overcome, and requires attention to consistency, organization and sane API design.

Have you ever written a guide to basic or fundamental JavaScript techniques?

jQTouch: Build iPhone Apps With JavaScript

02 Mar 2010 | By Ric Roberts | Comments | Tags iPhone jQuery libraries tutorials

jQTouch is a jQuery plugin for mobile web development. It lets you create native-feeling iPhone applications using just HTML, CSS and JavaScript by taking advantage of native webkit animations and by capturing events such as swipes and orientation changes.

As the author, David Kaneda, writes in the online documentation, it’s easy to get started: Just include jQuery and jQTouch along with any themes and extensions in your page, then initialize jQTouch with any options.

So the head of your document might look a bit like this:

<head>
  <meta charset="UTF-8" />
  <title>jQTouch Example</title>
  <style type="text/css" media="screen">@import "../../jqtouch/jqtouch.min.css";</style>
  <style type="text/css" media="screen">@import "../../themes/jqt/theme.min.css";</style>
  <script src="../../jqtouch/jquery.1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="../../jqtouch/jqtouch.min.js" type="application/x-javascript" charset="utf-8"></script>
  <script src="../../extensions/jqt.location.js" type="application/x-javascript" charset="utf-8"></script>
  
  <script type="text/javascript" charset="utf-8">
    var jQT = new $.jQTouch({
      icon: 'jqtouch.png',
      addGlossToIcon: false,
      startupScreen: 'jqt_startup.png',
      statusBar: 'black'
    });

    // ... more js here ...
  </script>
</head>

There are a few extensions provided (including one for access to the iPhone’s geo-location features, and another for auto-setting the title in the toolbar from the referrer page), but it’s possible to add your own by writing a function and passing it to $.jQTouch.addExtension().

(function($) {
    if ($.jQTouch)
    {
        $.jQTouch.addExtension(function Counter(jQTouch){
            var mycount = 0;          
            function addOne() {
                ++mycount;
            }
            function getCount() {
                return mycount;
            }
            return {
                addOne: addOne,
                getCount: getCount
            }
        });
    }
})(jQuery);

It’s even possible to make your jQTouch sites run offline, like a native iPhone app, by using HTML5’s Cache Manifest feature.

A great way to get started with jQTouch is by exploring the demos that David has provided in the download. These cover all of the features I’ve mentioned here, plus lots more besides: I’ve only scraped the surface.

If you want to dig deeper, there’s a screencast on PeepCode, and online in a Creative Commons O’Reilly book called Building iPhone Apps with HTML, CSS, and JavaScript.

Ruby vs. JavaScript Metaprogramming

01 Mar 2010 | By Alex Young | Comments | Tags ruby metaprogramming

Ric sent me Metaprogramming: Ruby vs. JavaScript, and at first I thought it looked pretty basic. However, I’ve noticed a lot of DailyJS readers are experienced ruby developers, and there are some good pointers in this article for rubyists.

For example, if you’re used to the metaclass in ruby, you might over-think metaprogramming in JavaScript:

To be honest, there’s not much to say about the JavaScript example because it is so simple. We avoid the whole metaclass business because JavaScript uses prototypal inheritance. This means that Javascript does not distinguish between classes/prototypes and instances and, therefore, we can add our desired behavior directly to the instance.

On a related note, I’ve previously done a lot of JavaScript DSL experimentation and stretched the limits of stylistically acceptable JavaScript. In Fear and Loathing in JavaScript DSLs I explain various techniques for giving the illusion of a friendly DSL. However, the best JavaScript libraries all seem to avoid this and make their interfaces more explicit, so I’ve never felt 100% comfortable with the approaches in that article.

Eloquent JavaScript

26 Feb 2010 | By Alex Young | Comments | Tags books

Eloquent JavaScript is an “opinionated guide to programming” written by Marijn Haverbeke. It’s been around for a few years now, but if you haven’t seen it before it’s definitely worth a look. It has 14 chapters with two appendices, and is available for free!

It covers important topics like functional programming, modularity, events, and some interesting obscure control structures. The text includes verbose examples complete with syntax highlighting. Haverbeke even references libraries like jQuery and Prototype.

Let's Make a Framework: Library Architecture

25 Feb 2010 | By Alex Young | Comments | Tags web frameworks tutorials lmaf

Welcome to part 1 of Let’s Make a Framework, a series of posts about building a JavaScript framework. In this part I’m going to discuss library architectures, and lay down the design for our framework.

This series is designed to be educational, rather than create the next big thing in JavaScript. To keep the spirit educational, I’ve decided to name the framework turing.js. Why? Well, if you don’t know much about Alan Turing then you might like to learn a bit about him. See? The framework is already helping teach computer science history!

Required Reading

I’ll refer to these frameworks in this part:

Style

If you embark on an involved open source or private project, you’re likely to work with other people. It’s important to be upfront about the goals of the project and the style of development.

These are the practices I will use to develop this framework:

  • Verbose: Variable and method names should be verbose so things are easy to find and understand
  • Portable: Browsers and console should be catered for
  • Explicit: Code should be quick to understand
  • Comments: Let’s keep comment noise down. Comments should be succinct. TODO and FIXME are acceptable.
  • Simple: Keep code simple. Let’s not bore readers!
  • Indentation: Two spaces
  • Semicolons: People might want to minify this library — let’s keep simicolons!
  • Quality: JsLint and reader comments!
  • Testing: Test first development for both browsers and console
  • Versioning: GitHub to the rescue

High Level Framework Structure

The first question to ask about a JavaScript framework’s structure is: how self-contained is it? In 2005 we were blown away by Ajax and the yellow fade technique, so people flocked to libraries that made those techniques easy. Now in 2010 we’re writing server-side JavaScript and creating sophisticated front-end behaviour. We can no-longer afford to use frameworks that aren’t careful about their namespacing.

Take a look at the current stable prototype.js. It modifies the prototypes of a lot of native objects. It also provides a lot of top-level objects. The BBC specifically designed Glow to avoid this, and literally everything is namespaced. This feels strange if you’re used to Prototype, because Prototype attempts to simplify browser-based JavaScript. Prototype makes complex Array manipulation much easier cross-browser, but with Glow you need to remember to use glow.lang.toArray and other utility methods.

The lesson here is that you trade off usability to play nice with other frameworks. Due to the way JavaScript works though, it’s possible to use both approaches — our library could have configuration options to extend native objects.

This framework will be more like Glow — this will remove a lot of hidden magic when using it. People using it to learn JavaScript should be able to see the difference between what browsers and CommonJS provide.

Another interesting point about Prototype is it quickly defines high-level structural code which it reuses internally. It defines Object.extend and Class, then reuses these to build fundamental features:

var Hash = Class.create(Enumerable, (function() {
  function initialize(object) {
    this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
  }

Helper Methods

MooTools, jQuery and Prototype all define helpers to reduce the effort required to call commonly used functions:

// Prototype
function $H(object) {
  return new Hash(object);
};

// MooTools
function $H(object){
  return new Hash(object);
};

It would be nice to include quick access to helper methods, but as I said previously where turing.js begins and ends needs to be clear to the newcomer. Therefore, if these are to be used they should be succinct but clear.

If you taught someone JavaScript with jQuery, would they even realise browsers don’t have $()?

Initialisation

Most frameworks have wrappers for initialisation and metadata about the library. MooTools and Prototype use one broadly similar approach, then jQuery and Glow use another.

var MooTools = {
  'version': '1.2.5dev',
  'build': '%build%'
};

var Prototype = {
  Version: '<%= PROTOTYPE_VERSION %>',
  ...
}

(function( window, undefined ) {
  var jQuery = function( selector, context ) {
      // The jQuery object is actually just the init constructor 'enhanced'
      return new jQuery.fn.init( selector, context );
    },
    ...
    jquery: "@VERSION",
    ...
  }

  // Expose jQuery to the global object
  window.jQuery = window.$ = jQuery;
})(window);

Glow and jQuery both use an anonymous function, then expose themselves by writing an attribute to window. This is the approach I’ll use for turing.js.

Modules and Plugins

jQuery, MooTools and Glow have tried hard to be modular. Let’s use a similar approach, with a file naming scheme like this:

  • turing.core.js
  • turing.functional.js

After creating a turing variable that will be exposed to the global scope, we can define our modules on it as functions or objects.

Let’s Get Coding

I’m going to use my riot.js library to write unit tests, because it’s a simple unit testing library that is pure JavaScript.

You might think that testing a library framework stub is pointless, but we still need to make sure it sets things up properly in browsers and in the console. I’m going to run my tests in Rhino and Firefox.

The core test should check the following:

  • turing is instantiated
  • turing has properties we can read — let’s set a version number

The test code looks like this:

Riot.context('turing.core.js', function() {
  given('the turing object', function() {
    should('be global and accessible', turing).isNotNull();
    should('return a VERSION', turing.VERSION).isNotNull();
    should('be turing complete', true).isTrue();
  });
});

Putting this together, we get:

(function(global) {
  var turing = {
    VERSION: '0.0.1',
    lesson: 'Part 1: Library Architecture'
  };

  if (global.turing) {
    throw new Error('turing has already been defined');
  } else {
    global.turing = turing;
  }
})(typeof window === 'undefined' ? this : window);

Here’s how it looks in Rhino:

js> load('turing.core.js');
js> print(turing.VERSION);
0.0.1
js> print(turing.lesson);
Part 1: Library Architecture

And in a browser:

>>> turing
Object { VERSION="0.0.1", more...}

Until Next Week…

I’ll continue this series next Thursday. It took me three hours to research and write this article, so I think I’m due a few beers now.

The code is on GitHub: alexyoung/turing.js

FireRainbow

24 Feb 2010 | By Alex Young | Comments | Tags firefox firebug addons

FireRainbow is an add-on for Firefox and Firebug that adds themable syntax highlighting. It uses the JavaScript library CodeMirror to perform the highlighting, and has CSS themes. You can get the themes off firerainbow/themes on GitHub and paste them into the Colors tab within Firebug.

The performance is good, and it makes Firebug that little bit more usable and customised.

Another useful Firebug plugin is Eventbug. I also wrote a post about Eventbug.

Book Review: Advanced JavaScript

23 Feb 2010 | By Alex Young | Comments | Tags books reviews

Advanced JavaScript is an eBook by TJ Holowaychuk. It includes a PDF and sample source code, and costs $4. The book covers concepts like closures and scoping, prototypal inheritance, metaprogramming, testing with JSpec, and creating a jQuery clone.

Advanced JavaScript starts without much fanfare — there’s no preamble or introduction — it explains scope and var before you’ve even had a chance to start your coffee. The style is pragmatic and straightforward. Simple code examples frequently highlight ideas, and other programming languages are mentioned to give a sense of familiarity. Chapter 2, which covers prototypal inheritance, is particularly useful for those of you who aren’t full time JavaScript developers, because it draws sensible parallels with traditional OO classes. Holowaychuk also presents a simple Class implementation that features inheritance and the ability to append methods.

The metaprogramming chapter deals with an example based on Sinatra. This is based directly on Holowaychuk’s Express project, which is a JavaScript Sinatra clone. The example is based around being able to define methods for each HTTP expression using metaprogramming:

Although we could simply copy and paste the get() function above to start cre- ating our del(), put() and post() functions, we will take a meta-programming approach to solve the problem.

The next chapter deals with testing, using Holowaychuk’s other project, JSpec. This is a Behavior Driven Development (BDD) style of testing. This leads nicely into Chapter 5. Creating a jQuery Clone, which explains how to create a jQuery clone using BDD. This should appeal to those of you who find it difficult to visualise how test-first development might be used for JavaScript projects. It’s also a good example because most of us use jQuery without really understanding how it works.

The final chapter, Tools Of The Trade, covers popular libraries and frameworks.

Advanced JavaScript neatly links together TJ Holowaychuk’s work to produce a coherent guide to writing modern JavaScript. He references Ruby few times throughout the book, which will appeal to those of you who are full-time Rubyists but still trying to understand the deeper aspects of JavaScript. Given that it’s only $4 it’s a great deal too — highly recommended.

eReaders

I used Calibre to copy the PDF to my Kindle, and the formatting wasn’t great. The header and footers and table of contents need to be removed.

Uniform - Sexy Forms With jQuery

22 Feb 2010 | By Ric Roberts | Comments | Tags jQuery libraries css

Uniform is a jQuery plugin from Pixelmatrix design which lets you style form elements such as checkboxes, drop down menus, radio buttons, and file upload inputs in a consistent and accessible way across different browsers (unfortunately, this doesn’t include IE6 at the moment).

To use it, just link to the uniform JavaScript and css files from your html page, and then call the uniform function against the form element(s), passing in any parameters. Full details of the parameters are available on the Uniform site.

$(function(){ $("select").uniform(); });

You don’t need to just stick with the default style: you can design your own or download others from the Internet.

Weekend Reading

19 Feb 2010 | By Alex Young | Comments | Tags weekend fun games

Assuming you’re not going to be hungover or… working all weekend, here are some tasty links from my DailyJS link folder.

I Can’t Believe It’s Thomas Fuchs Again!

I Can’t Believe It’s Not Flash will strike a chord with many people. It’s a presentation by Thomas Fuchs about exciting things like WebGL. He mentions SceneJS which looks ridiculously fun.

11 Tips for Creating Great MooTools Plugins

11 Tips for Creating Great MooTools Plugins by prolific JavaScript blogger Ryan Florence is about writing better MooTools plugins. He also has some good advice about writing JavaScript in general:

Write methods to do one thing only

Create options for things that the class doesn’t need

Return this with most methods

Never mind about the plugins, I agree!

Balldroppings

Load up balldroppings then keep increasing the ball drop rate until your browser explodes.

Pong

Browser Pong. Have you ever see this version of Pong? It’s hilarious.

Let's Make a Framework

18 Feb 2010 | By Alex Young | Comments | Tags web frameworks lmaf

Let’s Make a Framework is a new series about JavaScript web frameworks that I’m starting right now on DailyJS. It will appear every Thursday in your feed reader until it either drives me crazy or I complete every part.

I’m going to document what goes into a JavaScript framework, and build one as the series progresses. It’s not going to be the next jQuery, it’s going to be purely an educational exercise for the reader.

I’m going to cover the following juicy topics:

  • Library architectures
  • Functional programming
  • Selectors
  • Events
  • Ajax
  • Animation
  • Module loading
  • Plugin architecture

Some parts, especially selectors, will be spread over multiple posts. This is because trying to cram them into one post will kill me, and I don’t want you to fall asleep.

Along the way I’ll hit on some fundamental parts of modern web JavaScript:

  • Browser capability detection
  • Clean, reusable API design
  • Benchmarking and performance
  • Writing minifier-friendly JavaScript
  • Using GitHub!

Do you have a name idea for this framework? If not I’ll name it something boring… Post in the comments or message us with @dailyjs!

Getting Started With Emile

17 Feb 2010 | By Alex Young | Comments | Tags animation css

Confused about how to use Emile, the mini-framework for CSS-based JavaScript animation? Well you’re in luck, because I’ve spent a good few days experimenting with it.

Emile allows you to animate CSS properties, transitioning between them. You can animate more than one at a time, and stack them using callbacks. You can also use your own easing functions. That’s almost all you need to know!

Basic Usage

Usage looks like this:

emile(element, CSS properties, { options });

The currently available options, in order of how much you’ll need to use them, are:

  • duration: The length of the animation in milliseconds
  • after: Code to run after the animation has finished
  • easing: An easing function to control timing that takes a number and is expected to return one

Animating a Property

This will fade out the background colour of an element:

emile($('example_1'), 'background-color: rgb(0, 0, 0)', {duration: 500});

Run | Reset

Moving Something

This will move an element that sits within flow (rather than position: absolute):

emile($('example_2'), 'margin-left: 200px', {duration: 500});

Run | Reset

Move with Custom Easing

You can provide an easing function. This allows you to control timing. This example is based on Thomas Fuchs’ presentation at Fronteers 2009.

function bounce(pos) {
  if (pos &lt; (1 / 2.75)) {
  return (7.5625 * pos * pos);
  } else if (pos &lt; (2 / 2.75)) {
  return (7.5625 * (pos -= (1.5 / 2.75)) * pos + .75);
  } else if (pos &lt; (2.5 / 2.75)) {
  return (7.5625 * (pos -= (2.25 / 2.75)) * pos + .9375);
  } else {
  return (7.5625 * (pos -= (2.625 / 2.75)) * pos + .984375);
  }
}
emile($('example_3'), 'margin-left: 200px', {duration: 1500, easing: bounce});

Run | Reset

Combination

Animating more than one property is easy:

emile($('example_4'), 'margin-left: 200px; background-color: #000', {duration: 1500, easing: bounce});

Run | Reset

After Callback

Using the after option lets you queue an unlimited number of animations:

emile($('example_5'), 'margin-left: 200px; background-color: #000', {
duration: 1500,
easing: bounce,
after: function() { emile($('example_5'), 'margin-left: 0; opacity: 0.0', {duration: 1500}); }});

Run | Reset

Gotchas

Did you notice the combination demo discolours the rectangle as it bounces back? The easing function changes the colour as well as position, which isn’t necessarily what you might expect. Keep this in mind when animating properties with easing functions.

Why Emile?

Emile seems so simple we barely need a library, right? Well… animating CSS properties isn’t that simple. Colours and numbers need to be normalised, CSS properties need to be converted to the internal names used by the DOM. What Fuchs provides with Emile is actually a very shrewd observation of the bare minimum needed to create a workable animation framework.

emile_demo.html

jQuery Plugin Roundup: Ketchup, Quicksand, Fitted

16 Feb 2010 | By Alex Young | Comments | Tags jquery plugins

Welcome to the jQuery Plugin Roundup, episode 2. Remember you can send your plugins in for review through our contact form or @dailyjs.

Ketchup – Simple Form Validation

Ketchup provides lots of useful form validations using the class attribute on input elements. For example:

<div>
  <label for="ex1_username">Username</label>
  <input type="text" id="ex1_username" class="validate(required, username)" />
</div>

Validations can be combined like this:

<input type="text" class="validate(required, username, rangelength(3,20))" />

Visit ketchup-plugin on GitHub to download.

Quicksand – Reordering and Filtering

Quicksand lets you reorder and shuffle items with a cool animated effect. I have a feeling this will work particularly well for mobile webkit web apps.

Usage looks like this:

$("#content").quicksand($("#data > li"), {
		duration: 1000,
		easing: "easeInOutQuad",
		attribute: "data-id",
	}
);

Visit quicksand on GitHub to download.

Fitted – Clickable Content Blocks

Fitted is a simple plugin for making a container clickable. This is useful when you’ve got quote or abstract that links to full content.

Usage is simple: $('.clickable_class').fitted();

wtfjs

15 Feb 2010 | By Alex Young | Comments | Tags javascript humour

wtfjs is a blog of JavaScript’s irregularities, inconstancies and unintuitive aspects. The author posts humorous code snippets which are similar to the bad parts from Crockford’s JavaScript: The Good Parts.

Other than the obvious examples based around the confusing nature of falsy and NaN, there are some interesting examples that might test your knowledge of JavaScript:

("foo" + + "bar") === "fooNaN"
(x=[].reverse)() === window // true

Am I suffering from a kind of blindness due to writing JavaScript for too long, or does the following make sense?

"string" instanceof String; // false
(new String("string")) instanceof String; // true

Of course it’s false, it’s a string literal rather than an instance of String! Is it useful to distinguish between string literals and instances of String?

Opera JavaScript Performance in 10.5

12 Feb 2010 | By Alex Young | Comments | Tags opera performance

The pre-release of Opera has a new JavaScript engine called Carakan (read more in Jens Lindström’s post). This changes Opera’s approach slightly, because previous versions attempted to minimise memory usage, whereas Carakan aims to focus on execution speed. According to SunSpider, Carakan is about 2.5 times faster than their previous engine.

One of the main reasons for the new engine’s performance improvements is native code generation. This is indicative of Opera’s new approach in general — they’ve been attempting to Cocoaify their Mac version for example.

Other major changes in Carakan are register-based bytecode generation and automatic object classification. According to Jens:

In the new engine, each object is assigned a class that collects various information about the object, such as its prototype and the order and names of some or all of its properties. Class assignment is naturally very dynamic, since ECMAScript is a very dynamic language, …

… We use this to cache the result of individual property lookups in ECMAScript programs, which greatly speeds up code that contains many property reads or writes.

Carakan is bringing some radical changes to Opera’s engine. It’s possible that the native code approach was also partly inspired by V8’s approach, and Jens doesn’t mention any deeper changes to areas like garbage collection or threading.

Max/MSP and JavaScript

11 Feb 2010 | By Alex Young | Comments | Tags music graphics

In a previous life I was heavily into digital music production. One popular tool in that area is Max/MSP — a visual programming language for music and graphics. It’s not just used by hackers, many musicians and artists also use it. In some ways it’s more accessible than Processing, and is more adept at audio.

Max/MSP allows you to draw networks of audio processing units and manipulate them in real time. You can interact with MIDI hardware as well.

What’s interesting about Max/MSP is in recent years they’ve added a JavaScript API. The API uses globally available functions and objects, so the API feels a bit like Processing. The company that makes Max/MSP, Cycling74, has a set of tutorials up called JavaScript in Max.

You can use JavaScript to create UIs with OpenGL, so you could create interesting animations as well as scripted audio processing.

If you’d like to see some example patches, try searching for JavaScript in the Max Objects Database. Max is actually commercial software (it starts at $250), but there’s a 30 day demo if you’re interested in experimenting. If you’ve got a Mac you can load Quartz Composer to see a similar type of tool which is focused on video.

1 2 3 4 5