« December 2005 | Main | February 2006 »

The world is your programmable oyster

Jan 30 by Andre in Ajax » , Web » , Web 2.0 »
Programmable Web is a repository of Web 2.0 APIs and mashups. I found this via TechQuik.

Digg anxiety: a Web 2.0 neurosis

Jan 27 by Andre in Misc »
I hereby coin a new term. When this goes on Wired's buzzword watch, remember you saw it here first.

digg anxiety: the fear that right now, while you're looking at something else, there are cool stories going through digg which you are missing.

We didn't really have this problem with Slashdot -- I think it has to do with the sheer volume of stories on digg . . .

Good stuff in XHTML 2.0

Jan 27 by Andre in Web »
Part two in The Future of HTML series talks more about XHTML2.0. APIs are likely to include:
  • An API for dealing with the browser Window object
  • DOM Level 3 Events and XPath specifications
  • An API for timed events
  • APIs for non-HTTP networking, such as XMPP or SIP
  • An API for client-side persistent storage
  • An API for drag and drop
  • An API for monitoring downloads
  • An API for uploading files

[XHTML2.0 will] allow any element to have a src attribute. A browser will then replace the element's content with that of the content at the URI. In the simple case, this is an image. But nothing says it can't be SVG, XHTML, or any other content type that the browser is able to render.

Anonymous login for NYTimes

Jan 26 by Andre in Misc »
From http://bugmenot.com/view.php?url=nytimes.com

Username jetix
Password kedafu

Samsung A900 vs Moto RAZR

Jan 26 by Andre in Gadgets » , Misc »
a900mid.gifNYTimes has a good article on the Samsung A900 ("Blade") vs the Moto RAZR.

In a nutshell: Same formfactor and basic aesthetic; Samsung has superior software, more memory, and external, dedicated buttons for playing music. RAZR is slightly slicker looking.

Also, Samsung has built-in speech to text software so you can dictate text messages! Nice.

Javascript: Object Orientation

Jan 22 by Andre in Ajax » , Javascript » , Web » , Web 2.0 »

An OO approach is a key part of your Javascript/Ajax programming arsenal. There are multiple ways to program Javascript in an object-oriented way. The Prototype library adds some helper constructs to facilitate object orientation, as do many other Javascript libraries. Regardless of which framework you use (or if you choose to use none at all), an object-oriented approach can make your Ajax programming easier.

Here, I'm demonstrating a basic syntax for OO; you can use this syntax literally, or use it to enhance your understanding of the various framework-based OO approaches available out here.

Defining the Class

In Javascript, classes are defined as functions. The "new" keyword together with the function gives you new instances of the class. Here's an example:
// a Person class
function Person (sName, nAge) {
	this.sName = sName;
	this.nAge = nAge;
} 

// add a method to the class by adding a function to its prototype
Person.prototype.tellMe = function() {
  return ("My Name is "+this.sName+". I am "+this.nAge+" years old");
}
That's all there is too it. You have now defined a class (Person), with one method (tellMe).

Using the Object

To use the Person class we just defined:
var oPerson = new Person("Bob", 28);
alert (oPerson.tellMe());
. . . will give us:

Where's the Constructor?

In this example, all the code inside function Person() is the constructor -- this code gets executed each time you use the function to create a new instance of the class, and sets the members of the instance (sName and nAge) to the values passed to the function.

There's lots more to OO Javascript programming

You can model inheritance and more with Javascript. A good place to learn more is webreference's Object-Oriented Programming with JavaScript series.

Javascript: Adding functionality to built-in classes

Jan 20 by Andre in Ajax » , Javascript » , Web »
Strings, arrays, and all other classes in Javascript are extensible, and it's extremely easy to add methods to them. An example is the best way to demonstrate; this example shows a "trim" method (strip whitespace from the beginning and end of string) added to the built-in "string" class:
String.prototype.trim = function () {
  var sNew = this.replace(/^\s*/, ""); // strip whitespace from the beginning of the string
  sNew = sNew.replace(/\s*$/, ""); // strip whitespace from the end of the string
  return sNew; // return the mutated string
}
You can call the method on any instance of string:
var sString = "a value from an HTML form . . . ";
sString = sString.trim();

What you need to know: Prototypes and the "this" keyword

Everything in Javascript has a prototype. Any functions you add to the prototype are automatically available to each and every instance of the class. Accessing the prototype is as easy as specifying [class].prototype. So in the example above, we added a function (trim) to string's prototype: string.prototype.trim=function(){...};

The other key is the "this" keyword. Whenever you are coding a "prototype" function, you need access to the particular instance. The "this" keyword lets you do it. At runtime, the "this" keyword resolves to the actual instance of the object, in this case a String.

Note that this example does not mutate the string on which you called the method. Rather, it returns a new string with whitespace removed. The original instance is left unchanged. If you were to do the following:

var sString = " a value from an HTML form . . . ";
sString.trim();

. . . sString would not change. Calling the trim() method would produce a new string, which would then be thrown away because it isn't being assigned to anything.

Javascript: optional, defaultable function arguments

Jan 18 by Andre in Ajax » , Web »
This is an incredibly useful real-world construct for your Javascript and Ajax programming efforts. As you make your Javascript code encapsulated and reusable, you inevitably need to parameterize your functions so that some of the arguments are optional. There are multiple of ways of doing this, but my coding has benefited greatly from a consistent methodology and syntax. Here's an example:
function doSomething (sWhatever, oOptions) {
  var oOptions = augment({
      sOptOne: "foo",
      bOptTwo: false
    }, oOptions );

  // sWhatever is a regular argument. We assume it's always going to be passed
  alert(sWhatever);

  // sOptOne and bOptTwo are optional;
  // they are defaulted to "foo" and false, respectively
  alert(oOptions.sOptOne);
  alert(oOptions.bOptTwo);
}
The function defined above can be called in a number of different ways:
  • doSomething("First value"); -- this invokes the function without either of the optional arguments, so sOptOne and bOptTwo both get their default values ("foo" and false, respectively).
  • doSomething("First value",{bOptTwo:true}); -- in this case, the bOptTwo argument is specified in the functional call, so it's value is true, rather than the default value of false.
  • doSomething("First value",{sOptOne:"Yahoo",bOptTwo:false}); -- here, both the optional arguments are provided.

The key here is that the optional arguments are specified by name, rather than position. Therefore, you can leave any of them out, and they assume the default value you specified in the function itself.

The augment() Function

The "augment()" function is what makes it all happen. This function takes two or more objects, and augments the first object with properties from the second (or subsequent, of you pass more than one) object(s).

For defaultable arguments, the first object is the default values ( that's the {sOptOne: "foo", bOptTwo: false} part, and the second object is the oOptions object passed into our function.

Here is the augment function:

/*
  Augment an object by replacing its key:value pairs with those
  from other object(s), and adding pairs from other object(s) that don't
  exist in you.  Key:value pairs from later objects will
  overwrite those from earlier objects.
  
  If null is given as the initial object, a new one will be created.
  
  This mutates and returns the object passed as oSelf. The other objects are not changed.
*/
function augment (oSelf, oOther) {
    if (oSelf == null) {
        oSelf = {};
    }
    for (var i = 1; i < arguments.length; i++) {
        var o = arguments[i];
        if (typeof(o) != 'undefined' && o != null) {
            for (var j in o) {
                oSelf[j] = o[j];
            }
        }
    }
    return oSelf;
}

Optional, defaultable arguments are a powerful Javascript programming technique. They make it much easier to evolve your code, especially when you build "visual" objects -- objects that correspond to visual elements on the page.

Windows Vista and XP side by side

Jan 12 by Andre in Misc »
Bentuser has a nice article showing Windows Vista and windows XP side-by-side. Shows a lot of the visually attractive Vista goodies. Interesting also to see the ubiquity of as-you-type search throughout Vista.

vista.jpg 

Programmatically setting the "float" CSS property in Javascript

Jan 11 by Andre in Web »
IE and Firefox have different ways of doing this, and neither one is what you would expect.

In IE, it's myDiv.style.styleFloat="left";

In Firefox, it's myDiv.style.cssFloat="left";

Here's a full code block, with primitive browser detection included. This will work in both IE and Firefox:

if (document.all) {   // very basic browser detection
  var sFloat="styleFloat"; //ie
} else {
  var sFloat="cssFloat"; //firefox
}
var oMyDiv=document.getElementById("myId");oMyDiv.style[sFloat]="left";

Good CSS article

Jan 08 by Andre in Misc »
This is a good article on CSS, with solid real-world advice on cross-browser issues. Example: Setting WIDTH:100% in a DIV can cause it to not match the width of DIVs set to auto (the default) in IE.

Ajax Patterns - excellent resource

Jan 05 by Andre in Ajax »
Michael Mahemoff has assembled an excellent collection of Ajax Patterns at http://ajaxpatterns.org, in conjunction with his upcoming O'Reilly book.

What's in *your* Javascript try-catch blocks?

Jan 04 by Andre in Ajax » , JSLog » , Javascript » , Web »
For me, one of the best things about the Ajax movement is that it has legitimized usage of the Javascript language, which I have always enjoyed programming in anyway. With JS's new legitimacy comes recognition that we need more of the "real-world" constructs and practices that we all apply to other languages. Like Logging. And better error handling.

And try-catch blocks.

Which brings us to the question, what's in your try-catch blocks? What are you doing when you catch an error?. In some cases you want to take some specific action (redirect the user to another page, show a clear user-visible error, tell the user there's no point going on, etc.), but in other cases there's nothing you can really do for the user -- you just want to record the error so you can debug the problem as quickly as possible. If this was Java, PHP, Ruby, C#, or whatever, you would log an error and that would be that.

With Javascript, you can use JSLog, and log an error in your catch block. The code looks like this:
try {
    var foo = somethingRisky();
} catch (e) {
    jslog.error("Something risky failed! foo="+foo+"; error is "+e.message);
}


Which in turn would give you a JSLog display of:


This works great during development, when you probably have JSLog enabled, and are using it for debugging output anyway. As your code matures into production, you can leave the jslog.error() call there, even as you disable JSLog. If the page is behaving unexpectedly, you can temporarily expose JSLog output (either by switching the config_enabled setting back to true, or by including &enablejslog in the url; see here for details) and see the problem as it was logged in the catch block.

Basically, the problem is that output from the catch block needs someplace to go. JSLog gives it someplace to go, where it can be easily retrieved and inspected, in either a development or production environment. Read more about JSLog here.

Prototype and Scriptaculous in one file, < 50Kb

Jan 04 by Andre in Ajax » , Prototype »
Alister Cameron has combined the Prototype and Scriptaculous libraries into one condensed file: http://www.alistercameron.com/2006/01/05/prototypejs-scriptaculous-in-one-file-under-50kb/

Yahoo Javascript development center

Jan 04 by Andre in Ajax »
A bunch of good info and Ajax reference materials at http://developer.yahoo.net/javascript/

Comments & Feedback

Jan 03 by Andre in JSLog »
I would like to hear your comments and feedback on JSLog. Please leave your comments here, or drop me an email at andre {at} earthcode.com.