Activate your free membership today | Log-in

Monday, June 16th, 2008

Enhanced Class Inheritance with JavaScriptMVC

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:
  1. var Person = Class.extend({
  2.   init: function(isDancing){
  3.     this.dancing = isDancing;
  4.   },
  5.   dance: function(){
  6.     return this.dancing;
  7.   }
  8. });
  9.  
  10. var Ninja = Person.extend({
  11.   init: function(){
  12.     this._super( false );
  13.   },
  14.   dance: function(){
  15.     // Call the inherited version of dance()
  16.     return this._super();
  17.   },
  18.   swingSword: function(){
  19.     return true;
  20.   }
  21. });
  22.  
  23. var p = new Person(true);
  24. p.dance(); // => true
  25.  
  26. var n = new Ninja();
  27. n.dance(); // => false
  28. n.swingSword(); // => true
  29.  
  30. // Should all be true
  31. p instanceof Person && p instanceof Class &&
  32. 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:
  1. Class.extend(‘monster’,
  2.   // class methods
  3.   {
  4.     find: function(name){
  5.       return this.creatures[name];
  6.     },
  7.     // called whenever Monster is subclassed
  8.     extended: function(Class){
  9.       this.types.push(Class.className);
  10.     },
  11.     types: [],
  12.     creatures: {}
  13.   },
  14.   // prototype methods
  15.   {
  16.   // constructor
  17.   init: function(name){
  18.     this.name = name;
  19.     this.life = 100;
  20.     this.attack_stength = 20;
  21.     this.Class.creatures[name] = this;
  22.   },
  23.   attack: function(creature){
  24.     creature.life -= this.attack_stength;
  25.   }
  26. });
  27.  
  28. Monster.extend(’sea_monster’);
  29. Monster.extend(‘dragon’,{
  30.   find: function(name){
  31.     var found = this._super(name);
  32.     // Dragons’ spirits are raised when they feel wanted
  33.     found.life+=10;
  34.     return found;
  35.   }
  36. },{
  37.   init: function(name){
  38.     // call the inherited version of init()
  39.     this._super(name);
  40.     this.attack_stength = 50;
  41.   },
  42.   attack: function(creature){
  43.     // dragons hurt themselves a bit when they attack
  44.     this.life -= 5;
  45.     // call the inherited version of attack
  46.     this._super(creature);
  47.   }
  48. })
  49.  
  50. Monster.types; // => [’sea_monster’,'dragon’]
  51. var h = new Monster(‘hydra’);
  52. var a = new Dragon(‘albi’);
  53. a.attack_stength; // 50
  54. a.Class.className; // ‘dragon’
  55. a.attack(h); // h.life = 50, a.life = 95
  56. var d = Dragon.find(‘albi’); // returns albi instance, d.life = 105
  57.  

Posted by Ben Galbraith at 7:00 am
1 Comment

++++-
4.4 rating from 17 votes

Saturday, February 23rd, 2008

Ojay - a chaining wrapper for the YUI

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:
  1.  
  2. $('a#run-this-code').on('click', $.stopEvent)
  3.     .setContent('Running...')
  4.     ._('#example').animate({
  5.         height: {to: 0},
  6.         opacity: {from: 1, to: 0}
  7.     }, 0.5)
  8.     ._($.HTTP).GET('/service/hello.html')
  9.     .insertInto('#example')
  10.     ._('#example').animate({
  11.         height: {to: 80},
  12.         opacity: {from: 0, to: 1}
  13.     }, 0.7);
  14.  

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.

Posted by Chris Heilmann at 6:55 am
14 Comments

++---
2.9 rating from 40 votes

Wednesday, September 12th, 2007

ActiveState announces The Open Komodo Project

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

Posted by Rey Bango at 8:00 am
9 Comments

+++--
3.5 rating from 24 votes

Saturday, June 30th, 2007

How to write a Google Gadget

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.

Posted by Michael Mahemoff at 8:13 am
5 Comments

++++-
4.5 rating from 21 votes

Wednesday, January 31st, 2007

Eval’ing with IE’s window.execScript

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.

Posted by Michael Mahemoff at 3:40 pm
28 Comments

++++-
4 rating from 51 votes

Sunday, January 14th, 2007

JavaScript Scripting Essentials

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?

Posted by Rob Sanheim at 4:47 pm
11 Comments

++++-
4.2 rating from 26 votes

Sunday, December 3rd, 2006

Testable Ajax Seminar

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

Posted by Michael Mahemoff at 4:18 pm
2 Comments

++++-
4.4 rating from 17 votes

Tuesday, October 3rd, 2006

Dynamic Graphics in the Browser

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:

  1. SVG
  2. Canvas
  3. Dynamic images from the server
  4. VML
  5. Richer Plugin (e.g. Flash)
  6. CSS/DOM
  7. data: resource
  8. XBM

Posted by Michael Mahemoff at 6:21 am
12 Comments

+++--
3.6 rating from 32 votes

Wednesday, September 20th, 2006

AJAX MVC (so to speak)

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.

Posted by Chris Cornutt at 7:20 am
10 Comments

+++--
3.1 rating from 39 votes

Tuesday, September 19th, 2006

Objectifying JavaScript

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.

Posted by Chris Cornutt at 10:20 am
4 Comments

+++--
3.5 rating from 20 votes

Friday, September 15th, 2006

Eliminating async Javascript callbacks by preprocessing

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:

Posted by Chris Cornutt at 8:26 am
10 Comments

+++--
3.1 rating from 41 votes

Friday, August 25th, 2006

Lightbox using iFrames instead of AJAX

Category: JavaScript, Programming

The Find Motive blog has a quick tip for Lightbox users looking for a little bit different way to tdisplay the images. They show how to push the information into an iframe instead.

Particle tree's hack of Lightbox allows other content besides images to be put into a Lightbox, but it uses AJAX to pull the content into the box. For my purposes this is overkill because an AJAX call is loading an iFrame which results in 2 HTTP requests and for forms inside a lightbox this won't function the way I want. I want the form to act separately from the current page so the user will not be redirected when the form is submitted. To me this gives the UI a smoother feel. Here is the code section that I modified.

Here's the code:

JAVASCRIPT: