Instant Download of Premium Web Templates
2009 December | Java-ScriptGate.com

Java-ScriptGate.com - Java Script Is Difficult

Archive for December, 2009

Development

December 31, 2009

2010 New Year’s Resolution

I have a backlog of draft posts, and I’m going to start working my way through them. I had a very interesting semester, and the next should be even more interesting. I’m keen to resume sharing. Look for more posts to come.

JS and App

December 30, 2009

JavaScript Unit Testing

Our JavaScript Developer Survey results showed that a large percentage of readers don’t currently unit test their JavaScript. I’ve been unit testing my own JavaScript projects for a few years, which resulted in the creation of riotjs — for more on riotjs see my blog post: Riotjs: A JavaScript Unit Testing Framework

There are lots of JavaScript test frameworks. I’ve presented a summary below — there are both traditional unit testing libraries and behaviour-driven frameworks.

unittest.js

unittest.js by Thomas Fuchs has been used by many JavaScript developers since Scriptaculous became popular in 2006. It provides a test framework that is recognisable to Ruby developers, and the relationship between Rails and Scriptaculous further increased adoption in this group.

This library depends on Prototype and is usually run inside HTML templates rather than a JavaScript interpreter.

Tests look like this:

  new Test.Unit.Runner({
    testExample: function() { with(this) {
      var exampleVar = '1234';
      assertEqual('1234', exampleVar);
      assert(true);
    }}
    
  }, "testlog");

Fuchs uses with(this) to cut down unnecessary syntax — you don’t have to write tests this way though.

Setup and teardown methods are supported. Shoulda-style assertion names have also been added. This adds methods to the prototypes for common JavaScript objects, so it’s possible to write 'test'.shouldEqual('test').

unittest.js also includes a handy benchmark method, and the following assertions:

assertNotEqual(expected, actual) Inverse of assertEqual
assertNotVisible(element) Checks if an element has display: none
assertVisible(element) Inverse of above
assertInspect(expected, actual) Checks if expected is the same as actual.inspect()
assertEnumEqual(expected, actual) Ensured two enumerables are equal
assertIdentical(expected, actual) Comparison using ===
assertNotIdentical(expected, actual) Inverse of above
assertNull(obj) Is obj null?
assertNotNull(obj) Inverse of above
assertMatch(expected, actual) Performs a regex, where expected is the regex
assertType(expected, actual) Checks if actual.constructor == expected
assertNotOfType(expected, actual) Inverse of above
assertInstanceOf(expected, actual) Checks if actual is instanceof expected
assertNotInstanceOf(expected, actual) Inverse of above
assertRespondsTo(method, obj) Checks if obj has a method named method
assertReturnsTrue(method, obj) Ensured that the method named method called on obj returns true
assertReturnsFalse Inverse of above
assertRaise(exceptionName, method) Ensures calling method raises an exception named exceptionName
assertElementsMatch([elements], expression1, expression2, ...) Ensures the array of elements match the list of expressions
assertElementMatches(element, expression) A helper for the above assertion when supplying a single element

JsUnitTest

JsUnitTest is a port of unittest.js without the Prototype dependency.

JsUnit

Development for JsUnit started in 2001, and is based on JUnit. Like unittest.js, tests are designed to be run in a web browser. By using the build.xml Ant file, tests can be run against multiple browsers on a local machine, or on multiple remote machines.

JsUnit tests are grouped within a Test Page. Test pages contain your tests. If a Test Page has setUp or tearDown functions, they will be run before and after each test function. A function called setUpPage will be run once per Test Page.

Each test function is written prefixed with test:

function testExample() {
    assert(true);
}

The following assertions are available:

  • assert([comment], booleanValue)
  • assertTrue([comment], booleanValue)
  • assertFalse([comment], booleanValue)
  • assertEquals([comment], value1, value2)
  • assertNotEquals([comment], value1, value2)
  • assertNull([comment], value)
  • assertNotNull([comment], value)
  • assertUndefined([comment], value)
  • assertNotUndefined([comment], value)
  • assertNaN([comment], value)
  • assertNotNaN([comment], value)
  • fail(comment)

QUnit

QUnit is used by jQuery for its unit tests. To use QUnit, include qunit.js and qunit.css within a HTML file that can display the test results.

Tests look like this:

test("a basic test example", function() {
  ok(true, "this test is fine");
  var value = "hello";
  equals("hello", value, "We expect value to be hello");
});

The jQuery QUnit documentation has full examples.

jspec

jspec (by Yehuda Katz) is an RSpec inspired framework. Rather than traditional unit tests, jspec attempts to provide a behaviour-driven development approach.

This is best illustrated with an example:

jspec.describe("The browser environment", function() {
  it("should have Array.prototype.push", function() {
    Array.prototype.push.should("exist");
  });
 
  it("should have Function.prototype.apply", function() {
    Function.prototype.apply.should("exist");
  });
})

Tests are written with it() blocks and chained should() calls.

The GitHub repository is currently pretty spartan, with no documentation or README, but jspec is a good port for those of you who are familiar with RSpec or want a change from JUnit-style libraries.

JSpec

JSpec by visionmedia (who have cropped up frequently on DailyJS) is a much more fleshed out BDD library. The author has tried to keep it minimal, but it has a unique and friendly DSL. It’s possible to write “grammar-less” tests using plain JavaScript.

Jasmine

Jasmine builds on the ideas of the previous libraries to provide a BDD library that supports asynchronous tests — Ajax-friendly testing.

JS and App

December 29, 2009

Doodle.js

I’ve written a few posts about canvas-based animation and graphics libraries lately. Before moving on to another topic I thought I’d mention Doodle.js, which is a sprite-based canvas library. Doodle.js simplifies working with the canvas, and includes excanvas for IE support.

Code using Doodle.js looks like this:

(function(oo) {
 oo.canvas('#my_canvas');
 var box = oo.rect({x:25, y:25,
                    width:50, height:50, fill:"#ff0000"});
 box.draw(); //draw a red box with initial parameters
 
 box.modify({fill:'rgb(0,255,0)'}).translate(50,0).draw();
 box.modify({fill:'purple'}).rotate(-45).draw();
 box.modify({fill:'yellow'}).translate(50,0).scale(1.5).draw();
 box.modify({fill:'blue'}).transform(1.5,0,0,1.5,50,0).draw();
 
})($doodle);

As you can see, the API is fairly clean. There isn’t currently much documentation, but the author has written a length blog post with examples.

While Processing.js is a full drawing and animation system, and Raphael is a vector graphics library, Doodle.js provides a simple way of working with sprites.

Frameworks

December 27, 2009

WTFramework – Detect Which Framework A Site Is Using, The Easy Way

Tags: , ,

WTFramework Summary

WTFramework is a dead simple, and well designed way to detect which framework a site is using as well as version. Being primarily a JavaScript developer I was always looking through the source to find which framework a certain site was using. Or to see if the developer had done something particularly cool with my favorite framework MooTools. It was developed by Oskar Krawczyk and is implemented as a bookmark for any A grade browser. You simply drag it into your bookmarks bar and its installed. You can now use it on any site you visit. The notifications are “Growl” like and are very well designed. Kudos to Oskar on this one, a dead simple, but time saving tool.

Installation

  1. Visit The Site
  2. Drag the big red icon into your bookmarks.
  3. It is now installed.

Fortunately For Us

Oskar has a public Git Hub repository for this. So if needs be you can change it to suit your needs.

Gallery

London based Website Design Company is providing professional website design and website development services. They create a range of website applications and solutions - from secure ecommerce platforms to tailored content management system. Hampshire based Web design agency is specializing in ecommerce website development. Browse through our work portfolio on website designing. Our programming team focuses to deliver an ecommerce web design that produces great ROI.

JS and App

December 23, 2009

Conway’s Game of Life

Our recent post about Processing.js made me think about Conway’s Game of Life. If you haven’t come across it before, it’s a simulation that works like this:

1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbours dies, as if by overcrowding.
3. Any live cell with two or three live neighbours lives on to the next generation.
4. Any dead cell with exactly three live neighbours becomes a live cell.

I like to use this algorithm to experiment with new graphics libraries, so I had my own Processing version from back in 2005. I’ve ported it to Processing.js here conway-js.

I’ve also found lots of interesting pure JavaScript implementations. ConwayJS by Joseph Robert is my favourite. It’s pretty fast and allows you to draw cells with the mouse.

Another interesting one is game_of_life by sukhchander.

I’ve uploaded my Processing.js examples to DailyJS so you can see them without checking out the git repositories:

JS and App

December 22, 2009

JavaScript Particle System

After yesterday’s Processing.js article I discovered this post about creating a particle system with JavaScript and a canvas: Parcycle: A Particle System with HTML5 canvas.

You can view the effect in action in this demo: Parcycle

I found the use of globalCompositeOperation very interesting in this code. It allowed the author to make particles appear lighter when they overlap by using a drawing mode rather than detecting the colour on the canvas.

JS and App

December 21, 2009

Processing.js

Processing.js is a JavaScript/HTML canvas port of Processing. Processing provides a toolkit for programming images, animation and even games. It’s hosted in Java and provides its own mini-IDE. Processing.js can interpret Processing projects, but runs them in a browser that supports canvas.

If you’re familiar with Processing already you should be able to run some of your projects in Processing.js. Just create a simple HTML page with a canvas and include processing.js. The examples/ folder in the source distribution demonstrates how to do this using a script called init.js — this finds the canvas on the page and instantiates a processing object:

Processing(canvas, scripts[i].text);

Processing.js allows you to embed Processing scripts into HTML like this:

<script type="application/processing">
</script>

Calling Processing from JavaScript

If you’re new to Processing but have a lot of JavaScript you want to reuse, you can safely call Processing from your JavaScript code. I’ve prepared an example project, fire.js which demonstrates one way of mixing JavaScript and Processing. You can pass the current Processing environment to a JavaScript class like this:

void draw() {
  fire.update(this);
}

Keeping some level of separation between JavaScript code and “pure” Processing seems like a good way to avoid confusion if you ever port to another Processing platform.

Processing Basics

Every Processing project has setup() and draw() functions. In this case I’ve instantiated a Fire object and I’m passing this which is the current Processing object. Then I can access Processing’s functions from within my JavaScript class.

The Processing reference gives example code for all of the Processing functions. There’s a lot of drawing primitives like rect() and ellipse() — playing around with these is a good way to learn Processing.

Related Projects

ruby-processing is a Ruby port. It differs to Processing.js because it provides a Ruby-style version of the Processing API. Even CamelCase method names have been changed to underscores.

Although Processing.js and Processing are awesome projects, if you just want to draw vector graphics you’d be better off with something like Raphael. Processing is more suited to animated visualisations or interactive projects.

Frameworks

December 17, 2009

Making Every Specified Link Send Via Ajax Using MooTools

Tags: , ,

This is a relatively simple concept and is nothing to elaborate but I wanted to share a small piece of code that will take every link with the class of “ajax” and access it using AJAX instead of actually going to that page. This using the same Request instance which will keep it optimized and manageable. MooTools is going to make this nice and easy on us…

Usage

JavaScript

var ajax_request = new Request(
{
	onSuccess: function(responseText, responseXML)
	{
		$('message').set('html', responseText);
	}
});

$$('.ajax').each(function(item){
	var url = item.get('href');
	item.addEvent('click', function(event){
		ajax_request.options.url = url;
		ajax_request.send();
		return false;
	});
});

HTML

Sent Via AJAX
Also Sent Via AJAX
I am filled with the results of our AJAX requests.

Its incredibly simple so no demo for this. The important concept here is that we are using the same request and pulling the href attribute base on a class selection. So changing something from AJAX to regular is as easy as adding or removing the class “ajax”. Pretty cool eh?

JS and App

December 16, 2009

Node.js on IRC

Node.js makes writing IRC-related programs straightforward and super-efficient, thanks to its evented networking. Therefore it isn’t surprising that a lot of projects have appeared already.

I’ve been looking around for reusable JavaScript IRC libraries, and discovered the following projects.

IRC Daemon Demo

This IRC daemon demo presented at jsconf.eu/2009 demonstrates how to build a server. It has simple prototypal classes for channels and users, and parses IRC commands using a regex and a switch. It also uses node’s TCP library.

nodelog

nodelog is an IRC logger. This would be a good place to start if you’d like to build a JavaScript IRC bot. The client code is clear and reusable. The log.js file demonstrates how to use the irc.js library.

irccat-nodejs

irccat-nodejs is based on irccat which allows you to send messages to IRC using HTTP or a TCP socket. The client code is again fairly simple.

egret

egret is a command-line IRC client. The base code uses node’s TCP sockets and a hash to interpret IRC commands into English.

nodejs.irc

nodejs.irc is an IRC bot. It’s not finished yet, but the code is separated out and easy to follow.

aoibot

aoibot is similar to nodejs.irc, but it looks like the finished product will be less generic. Again, it’s unfinished, so I expect the author still has a lot of ideas and work to do.

Download Premium Web Templates Instantly
Download Website Templates For Free