Monday, December 18, 2006

Javascript Objects: immediate and procedural, and an intro to pseudoclasses

An Object in Javascript is similar to that of other languages - it's essentially a way of structuring information and code in named subvariables of a single variable.

For example, the Math object has chilren like floor(), abs() and sin(), which should have obvious definitions by their names.

What most people don't realize, however, is that Javascript functions are also objects. So are Arrays. And Strings. In fact, anything that's not just a number is an Object.

Another thing they don't often notice is that they can make their own with relative ease. The simplest way is to use Javascript's immediate Object notation:
var myObject = {'myString':new String(), 'immediateString':'A little text', 'aNumber':2.71};

This creates an Object, named 'myObject', with three members: 'myString', 'immediateString', and 'aNumber'. Now, for example, to get a the 'myString' member, you can reference it in any of two ways:
myObject.myString="Lorem ipsum dolor sit";
alert(myObject['myString']);

Now, if you're pretty experienced as a programmer, you'll notice that the first is standard object reference notation, while the second is 'hash table' or 'associative array' notation - which exposes a nice little quirk of Javascript: Objects are little more than associative arrays. The fact that they can hold both scalar and complex variables is inherited from the ability of Javascript to handle both types in ANY variable.

Continuing on, we'll move to procedural notation:
var myObject = new Object();
myObject.myString = new String();
myObject.immediateString = 'A little text';
myObject.aNumber = 2.71;

This defines the same object as before, except does it by defining each variable one at a time. It's more to type, but more human-readable.

Lastly, we'll implement a pseudoclass. What we try to do with pseudoclasses is to implement features of C++ classes using Javascript Objects.

The below class is nothing more than a shell; a good starting point for building, for example, DHTML widgets.

function myClass() {
//Constructor code goes here
//Something I do if Timeouts are going to be involved:
this.instance=myClass.instances.push(this);
//which allows me to use setTimeout thusly:
this.timeout = setTimeout("myClass.instances["+this.instance+"].doSomething();", 5000);
//the below doesn't work right, as 'this' from the calling context of setTimeout is thw window object
this.timeout = setTimeout("this.doSomething();", 5000);
}
myClass.instances=new Array();
myClass.prototypes.doSomething = function () {
//This is the format for your basic non-static function
}

myClass.calculateSomething = function () {
//This is the format for static functions
}

myClass.eventHandlers = Object();
myClass.eventHandlers.documentLoad = function (e) {
/* I like using this paradigm for storing all my event handlers
Usually, before attaching a function to an element, I'll
set element.myClass.control to this, capture any relevant data from
the event object, then call a nonstatic function to deal with
the event.

Quick quirk: The best way I've found to get the source
element of an event:
*/
var src = this;
if (window.event) src=window.event.srcElement;
/* Please note that that is definately not 'one-size-fits-all' code;
testing for window.event is a way to determine if you're using
IE. you should find a way to use that as the only condition
to determine how you retrieve your event's information
*/
}


Note: If anyone knows how to gather the name of a non-anonymous function from within its own constructor, please tell me.

AJAX: What it is, what it isn't, and what it can do

cool stuff you can do, and stupid stuff you shouldn't

So, this word, AJAX, has been thrown around for the past couple of years, but what is it? Most people will invoke the acronym at this point, 'Asynchronous Javascript And XML', but that's not more explanatory than saying GNU's Not Unix.

Essentially, AJAX is a programming technique. It utilizes a combination of technologies - wait, scratch that. Enough explaining buzzwords with buzzwords; I might as well be telling you it's Web 2.0.

AJAX is a way of writing interface code for an application that resides on a webserver (buzzword: Web 2.0 Application), using the old standard of Javascript-controlled HTML (buzzword: DHTML) in combination with the relatively-new-but-already-ubiquitous XMLHttpRequest object. The 'Asynchrounous' part comes from the fact that, if you don't feel like making your users wait on a request to be fulfilled, you can have the XMLHttpRequest object start, and run a callback when the request either completes or fails.

AJAX is NOT, on the other hand, a magic programming language or server-side technology that allows a web application to be amazing with little work. If anything, it's HARDER to write AJAX-enabled code than a regular application.

Why use it? Glad you asked.

The major complaint people have with doing things online, for example, in checking webmail, is that it's slow and feels clunky. Programming via an AJAX method, however, allows your application to gather new data without refreshing the page - something that solves a number of asthetic and usability headaches you'd only understand if you've been writing webpages since, say, 2000.

Meanwhile, it's not explicitly mentioned anywhere in the Web 2.0 buzz, but I like to think that AJAX, as a technique, benefits from the kind of organization that comes from an object-oriented programming model. Now, while JS doesn't have an explicitly defined class structure, you can create pseudo-classes that behave, by and large, like real ones - thus obtaining all the benefits (reduced namespace impact, making for fewer script collisions and shorter variable lookup times, confined scopes, the ability to abandon the global namespace in favor of thread-safety, and the 'this.' object) and headaches (rediculous variable names like imageCache.library[25].width) that come with object orientation.

You'll note I said thread-safety. Ok, while a Javascript app will rarely bring your system to its knees or cause memory leaks (they are possible), one thing it can't avoid is race conditions (for example, if two timed bits of script want access to the same variable). A simple mutex lock is easy to implement in Javascript, and can be shared by your classes.

Still, that's MUCH later.

The next few posts here will be:
Javascript Objects: immediate and procedural, and an intro to pseudoclasses
A Simple AJAX Class
A More Complex AJAX Class
DOM Level 1 v. DOM Level 0: Quirks and Quibbles
CSS: Accessing the Sheets

Intro

Welcome to less-than-mad science. The idea of this site is to perhaps explain some of the mysteries of more advanced areas of Javascript programming (for example, bringing your JS code up to the level where it could actually be refered to as 'programming').

Just to start, I expect that if you're reading this, you are somewhat comfortable with the basics of a C-syntaxed language, that is: how to use 'if', 'for', 'while', the 'this.' object; some of the core concepts in Javascript, that is, when to use 'var' and 'new'. I also expect that you be familiar with the integral objects found in Javascript, ie: String; Object; Array; Math; window; document; etc.

If you are unfamiliar with the basics of JavaScript, I can suggest a couple of sites, as well as a book:

Quirksmode - This site, by Peter-Paul Koch, is a combination of a lead-you-in-by-the-nose tutorial on HTML, CSS and ECMAScript, as well as a set of well-done object lessons on how to compensate for browser quirks. It's a useful resource for both the novice and the expert. You will essentially benefit at all levels from this guy's extensive exerience.

W3Schools - While it doesn't have the most complete tutorials on the internet, it does contain a complete object reference for ECMA Script, as well as nice little 'try-it' examples that allow you to write and test code right in your browser.

O'Reilly's Pocket Javascript Reference - This book is an essential resource for anyone who's even vaguely serious about web application development. Buy it.

The next post starts the first lesson: "AJAX: What it is, what it isn't, and what it can do"