Monday, June 16th, 2008
Category: JavaScript
, Programming
Brian Moschel from the JavaScriptMVC project wrote in to tell us about their recent efforts extending John Resig's earlier Simple Class Inheritance work.
In case you missed it, John's blog talked about his efforts to take the best of the many efforts to simulate classical inheritance in JavaScript and reduce them to a simple, easy-to-use piece of stand-alone JavaScript. Here's an example of the syntax he settled on:
JAVASCRIPT:
-
var Person = Class.extend({
-
init: function(isDancing){
-
this.dancing = isDancing;
-
},
-
dance: function(){
-
return this.dancing;
-
}
-
});
-
-
var Ninja = Person.extend({
-
init: function(){
-
this._super( false );
-
},
-
dance: function(){
-
// Call the inherited version of dance()
-
return this._super();
-
},
-
swingSword: function(){
-
return true;
-
}
-
});
-
-
var p = new Person(true);
-
p.dance(); // => true
-
-
var n = new Ninja();
-
n.dance(); // => false
-
n.swingSword(); // => true
-
-
// Should all be true
-
p instanceof Person && p instanceof Class &&
-
n instanceof Ninja && n instanceof Person && n instanceof Class
The JavaScriptMVC guys built on top of his work to add:
- Class level inheritance: Easily reuse functionality by inheriting class methods and using superclass methods the same way as instance methods
- Class initialization callbacks: Setup your classes and keep track of subclasses with callback functions invoked once during class initialization
- Introspection: Allow classes to behave differently based on the name of the class, similar to ActiveRecord
- Access to the instance's class and superclass: Write code that directly accesses class methods and objects from instance methods even when you don’t know the name of the class
Their stuff will be available as a plugin to JavaScriptMVC at some point in the future, but is available now as standalone JavaScript.
Here's a code sample of these new features at work:
JAVASCRIPT:
-
Class.extend(‘monster’,
-
// class methods
-
{
-
find: function(name){
-
return this.creatures[name];
-
},
-
// called whenever Monster is subclassed
-
extended: function(Class){
-
this.types.push(Class.className);
-
},
-
types: [],
-
creatures: {}
-
},
-
// prototype methods
-
{
-
// constructor
-
init: function(name){
-
this.name = name;
-
this.life = 100;
-
this.attack_stength = 20;
-
this.Class.creatures[name] = this;
-
},
-
attack: function(creature){
-
creature.life -= this.attack_stength;
-
}
-
});
-
-
Monster.extend(’sea_monster’);
-
Monster.extend(‘dragon’,{
-
find: function(name){
-
var found = this._super(name);
-
// Dragons’ spirits are raised when they feel wanted
-
found.life+=10;
-
return found;
-
}
-
},{
-
init: function(name){
-
// call the inherited version of init()
-
this._super(name);
-
this.attack_stength = 50;
-
},
-
attack: function(creature){
-
// dragons hurt themselves a bit when they attack
-
this.life -= 5;
-
// call the inherited version of attack
-
this._super(creature);
-
}
-
})
-
-
Monster.types; // => [’sea_monster’,'dragon’]
-
var h = new Monster(‘hydra’);
-
var a = new Dragon(‘albi’);
-
a.attack_stength; // 50
-
a.Class.className; // ‘dragon’
-
a.attack(h); // h.life = 50, a.life = 95
-
var d = Dragon.find(‘albi’); // returns albi instance, d.life = 105
-
Saturday, February 23rd, 2008
Category: Ajax
, Programming
, Yahoo!
JavaScript is a language that can be approached from many angles. Historically it was UI-driven web developers that started playing with it, but lately and with the advent of large JS applications "the world's most misunderstood programming language" is also written by people that feel much more at home in higher programming languages. The nature of JavaScript then can become a barrier for fluid and rapid development.
This is where in the best of cases developer specialization comes in - which is not cheap. Another way to tackle the issue is to use metaprogramming to make the end language behave in the way you want it to.
James Coglan got inspiration from Dustin Diaz' DED|Chain and wrote a chaining wrapper for the the YUI's DOM, event, animation and Ajax modules called Ojay.
He wraps up his intentions thus:
To me, expressiveness is not just ’syntactic sugar’, a tool to help you type fewer lines of code. It’s a core factor in how maintainable and well-designed your codebase is. We have a team made up of Java devs, a few Ruby enthusiasts and a couple of JavaScripters, and it’s crucially important to us that anyone can look at a piece of code and figure out what it does. Code should tell a story.
What this translates to is shown in this example:
JAVASCRIPT:
-
-
$('a#run-this-code').on('click', $.stopEvent)
-
.setContent('Running...')
-
._('#example').animate({
-
height: {to: 0},
-
opacity: {from: 1, to: 0}
-
}, 0.5)
-
._($.HTTP).GET('/service/hello.html')
-
.insertInto('#example')
-
._('#example').animate({
-
height: {to: 80},
-
opacity: {from: 0, to: 1}
-
}, 0.7);
-
I am not sure about the morale of this story, but I can see that we will see more and more of this sort of metaprogramming and skillset mash-up happening in the nearer future. Therefore it is great to start conversations early about how to tackle multidisciplinary teams writing code.
Wednesday, September 12th, 2007
Category: Programming
, Toolkit
ActiveState have announced the launch of The Open Komodo Project which will offer an open source code base from which to develop integrated development environments.
The Open Komodo Project, based on the award-winning Komodo IDE, is a new initiative by ActiveState to create an open source platform for building developer environments. The Open Komodo Project will create Firefox-integrated web developer tools that support the open web.
The Open Komodo Project aims to create a full-featured web development tool for client-side web development integrated with Firefox©, Mozilla's free, open source web browser, and based on the award-winning Komodo IDE. This new tool, codenamed Komodo Snapdragon, will be developed in collaboration with the open source community.
Best known for their ActivePerl, Komodo Edit and Komodo IDE development tools, ActiveState wanted to give back to the open source community which has long supported their products and efforts:
Meanwhile, our friends within the Mozilla Community were looking for tools and applications that advocate the open web. Since Komodo is built on the Mozilla platform and ActiveState has had a long-standing relationship with the open source community, making Komodo a part of the technology stack for the open web was an obvious choice, one that benefits both the open source community and ActiveState.
This announcement even got Dojo's Alex Russell all worked up:
Very few of the Web IDE vendors seem to really “get†the web, and along with the folks at Aptana and Panic, the ActiveState bunch have impressed the hell out of me with their constant support of Open Source, deep understanding of why webdev sucks, and what they can do to fix it.
The first technology preview is expected to be ready by early November along with access to a public source repository and the Open Komodo website.
Full information about the project can be found on their project page
Saturday, June 30th, 2007
Category: Google
, JavaScript
, Programming
, Widgets
I've written some notes on the Google Gadget API and how to write a gadget, targeted at developers who already know Ajax.
What's a Gadget?
- The gadget is an XML file sitting on your server. In my case, http://ajaxify.com/run/widgets/google/diggroundup.xml. It will get cached, so effectively it must be a static file.
- The user adds your gadget to their igoogle portal, or codes it into their own website, by specifying this URL (it may be done indirectly - via the gadget registry. You'll appear in the registry if you've submitted your gadget to igoogle.)
- The gadget is rendered as an iframe, so you have all the usual security constraints which stop you borking the portal and other gadgets. This also means you can't communicate with other Gadgets other than via than remote calls to a common third-party server (or has anyone tried hooking them together using the iframe-fragment identifier hack? ).
It's based on a Digg Roundup tool, where the gadget show Digg stories according to user preferences such as topic and whether to go for popular or upcoming stories.

Wednesday, January 31st, 2007
Category: JavaScript
, Programming
, Remoting
Plaxo's Joseph Smarr has been playing with on-demand javascript, i.e. downloading extra JS code after the page has already loaded. When you grab the code via a remote call and eval() it, it doesn't get into global scope. So here's how he dealt with it.
Here’s a simplified version of the situation we faced:
function loadMyFuncModule() {
// imagine this was loaded via XHR/etc
var code = 'function myFunc() { alert("myFunc"); }';
return eval(code); // doesn’t work in FF or IE
}
function runApp() {
loadMyFuncModule(); // load extra code “on demand”
myFunc(); // execute newly loaded code
}
The thing to note above is that just calling eval() doesn’t stick the code in global scope in either browser. Dojo’s loader code solves this in Firefox by creating a dj_global variable that points to the global scope and then calling eval on dj_global if possible:
function loadMyFuncModule() {
// imagine this was loaded via XHR/etc
var code = 'function myFunc() { alert("myFunc"); }';
var dj_global = this; // global scope object
return dj_global.eval ? dj_global.eval(code) : eval(code);
}
This works in Firefox but not in IE (eval is not an object method in IE). So what to do? The answer turns out to be that you can use a proprietary IE method window.execScript to eval code in the global scope (thanks to Ryan “Roger” Moore on our team for figuring this out). The only thing to note about execScript is that it does NOT return any value (unlike eval). However when we’re just loading code on-demand, we aren’t returning anything so this doesn’t matter.
The final working code looks like this:
function loadMyFuncModule() {
var dj_global = this; // global scope reference
if (window.execScript) {
window.execScript(code); // eval in global scope for IE
return null; // execScript doesn’t return anything
}
return dj_global.eval ? dj_global.eval(code) : eval(code);
}
function runApp() {
loadMyFuncModule(); // load extra code “on demand”
myFunc(); // execute newly loaded code
}
And once again all is well in the world.
Sunday, January 14th, 2007
Category: JavaScript
, Library
, Programming
Dan Webb asks what are your JavaScript essentials? Those bits and pieces you can't live without that get copy/pasted from project to project. His pragmatic list includes the $ function, getElementsByClassName, Dean's event handling, the JS 1.6 array methods, and the DOMContentLoaded event. His full script that he guarantees he _won't_ support is here.
Do you start with a full on framework or library no matter what the project size, or do you have a small script you use similiar to Dan's? Do you go with a clean slate until you really feel pain, or do you just swear off javascript and start with GWT or a drag and drop IDE?
Sunday, December 3rd, 2006
Category: Programming
, Recording
Googlers Joe Walnes and Adam Connors gave a presentation on testable Ajax back in September (we didn't cover it at the time) ... "Does my button look big in this? Building testable AJAX applications." at the Google London Test Automation Conference. The theme is how to automate website testing with all the complexity Ajax adds. They talk mostly about testing strategies and technologies (like JUnit), but also mention the importance of architecting for testability.
Direct Link
Tuesday, October 3rd, 2006
Category: Canvas
, Programming
, UI
Dynamic graphics inside the browser are starting to become a little bit more practical, thanks to increased support for Canvas and SVG. I recently discussed eight competing techniques for generating dynamic graphics in an Ajax application, each with their own implications for portability, usability, and performance.
The following techniques are descibed:
- SVG
- Canvas
- Dynamic images from the server
- VML
- Richer Plugin (e.g. Flash)
- CSS/DOM
- data: resource
- XBM
Wednesday, September 20th, 2006
Category: JavaScript
, PHP
, Programming
Ever feel like, when you're coing up that next great Ajax application, that you're doing the same things over and over again? Like there has to be something better out there to help you make development of common functionality a lighter and easier task? MVC (Model/View/Controller) just might be what you're looking for, and in this new posting on PHPied.com, they show you the basics of creating your own Ajax MVC framework.
This is sort of a framework thing to create AJAX applications, based on the MVC design pattern. Yep, I have a lot of buzzwords here, I admit, but this shouldn't be taken too seriously. I was doing a bunch of small projects lately and I found myself using something like this little framework, without even thinking about it. Then I thought about it and I found that the scripts and the organization of them may resamble MVC a bit. So how does MVC fit when you mix things like thin and fatter client, HTML, JavaScript, XMLHttpRequest, PHP and CSS?
They answer the question by comparing the "usual flow" of an Ajax application to the structure that MVC provides. They use PHP for some of the backend work, but they use Javascript (including some Yahoo UI libraries) to handle the interaction with the user (in the View). They also use an Ajax connection to grab data from the backend server and a little extra Javascript to push that content out to the page.
It's a pretty simple example of what can be done, but it gives you a good idea of how Ajax/advanced Javascript can be integrated very easily with the Model/View/Controller style of development. To check out a demo of this mini-app, click here, and to just grab the source files click here.
Tuesday, September 19th, 2006
Category: JavaScript
, Programming
Javascript is just like any other language - well, sorta. It has the power to make your web applications really earn their keep and perform for the user. It also can be confusing if things start getting pretty complex. Thankfully, there's something that can help you compartmentalize your code and make it simpler to use more modularly - the object oriented functionality Javascript offers. Don't know how to get started with it? Well, check out this new article over on Digital Web Magazine for a few tips.
As scripts get larger, functions become more interrelated. Suddenly, you’ve got ten functions on a page, six of them calling each other to accomplish one task, and another four working towards something else entirely. For someone taking a first look at this code, it certainly wouldn’t be immediately clear which were meant to work together and which weren’t. This is where objects come in.
The author, Jonathan Snook, gets down to the basics of objects in Javascript - what they are, how to create them, how to access them, and much more. If you've ever done any work with the popular libraries like Prototype or Script.aculo.us, some of this will look familiar. He even gets into design patterns in OOP for Javascript with setting up Singletons and Factory patterns.
Friday, September 15th, 2006
Category: Programming
, Toolkit
, XmlHttpRequest
According to Harry Fuecks in this post on the SitePoint PHP blog, using Ajax should be easier:
The Catch 22 of AJAX is, for the sake of an easy life, most of the time we want to write “synchronous code†but asynchronous is the only way to avoid some rather nasty usability issues. This means rather than being able to write simple code, as we’d like to. We’re required instead to handle this via callbacks, but that’s now introduced a whole load more potential issues.
These issues he mentions include requiring a global XMLHttpRequest object to be available and handling multiple calls to a javascript function (like if the user gets a little too impatient). To help combat these issues, Harry recommends a two projects out there that have the functionality to make life a little bit simpler:
Friday, August 25th, 2006
Category: