Featured Posts

Why Do We Need Google Closure? Why Google Closure?When a new JavaScript library arrives, a question is often raised reasonably: “Why does the world need another library?” while we’ve already had too many good ones like jQuery, Prototype, Mootools, YUI… you name it. To find the right answer, just have a look at the package offered by Google under the name of Closure project....

Read more

Simple Web Chat with Meteor Comet Server Comet is not really brand-new (Ajax) term today; however, with most of people how it works remains somewhat mysterious. I have a little hand-on experience with Comet when creating a hobby game project with DWR Reverse Ajax sometime ago. It (DWR) was simple to start and really worked but required a Java web server (Tomcat, Jetty...) that I found rather...

Read more

corMVC: An jQuery-based MVC Framework I know quite a few JavaScript MVC frameworks out there but corMVC is what makes me exited at most for a few reasons. corMVC stands for "client-only-required" Model-View-Controller and that means it does not depend on specific server-side technology. In case you want to demo something, it would be perfect if everything can be done on client side. Of...

Read more

Transparent PNG vs Transparent GIFBest IE6 “PNG Alpha-Transparency” Fixes You are likely living in civilized society with Firefox, Safari, Chrome or Internet Explorer 7/8 installed in your computers. Yet, some are still in the dark with the older Microsoft browsers named Internet Explorer 6 (IE6) or, worse, older versions. One of the most painful facts about IE6 is that it does not natively support PNG alpha-channel transparency. Microsoft...

Read more

  • Prev
  • Next

Prototype vs Class Inheritance in YUI 3

0

Posted on : 01/07/2010 | By : Jimmy Vu | In : Development News, Solution

As I mentioned in the post YUI 3.0 – Changes From the Root, YUI 3 is a radical evolvement of the framework. One of the most interesting features it provides with is about much better support for OOP.

YUI 3 supports two inheritance patterns via object prototype and “class”. Let’s examine the differences and advantages of each pattern.

Prototypal Inheritance in YUI 3

Suggested by Douglas Crockford, prototypal inheritance pattern is to deal with objects, i.e. objects inherit from objects. YUI 3 supports prototypal inheritance from its core; it means you can utilize the pattern by including the seed file only:

<script type="text/javascript" 
    src="http://yui.yahooapis.com/3.0.0/build/yui/yui-min.js"></script>

Now, for example, we have an object named animal:

var animal = {
    name: "Animal",
    level: "top",
    say: function() {
        return "I am an " + this.name + " at " + this.level + " level.";
    }
};
 
alert(animal.say()); // I am an Animal at top level.

And you want to create an elephant object that is an inheritance of animal. It’s so easy to do:

var elephant = Y.Object(animal);

Of course, you’ll need to modify the newly-born creature to make it a true elephant by overriding its parent properties and adding some new ones:

// override an animal’s property
elephant.level = "second";
 
// add elephant’s own properties
elephant.trunk = 1;
elephant.tusks = 2;

However if you want the elephant to say more about its own belongings, you’ll have to redefine say method completely.

elephant.say = function(){
    return "I am an " + this.name + " at " + this.level + " level."
        + " I have " + this.trunk + " trunk and " + this.tusks + " tusks.";
};
 
alert(elephant.say()); // I am an Animal at second level. I have 1 trunk and 2 tusks.

I think this pattern is quite easy to understand but before going forward to the next one, here are what we learn from it:

  1. We can create a new object that inherits all the properties and methods from an existing object.
  2. We can customize the new object by overwriting some/all of the members or adding new ones.
  3. The dark part is an overwritten property has no way to reference its parent’s property.

    Note: In this pattern, the child’s properties do not really overwrite its parent’s ones but they just take higher precedence. So if we delete a child’s method, the parent’s one will be back magically. For example:

    delete elephant.say;
    alert(elephant.say()); // I am an Animal at second level.

“Class” Inheritance in YUI 3

Yes, I know there are no true classes in JavaScript, however we can make constructor functions act like classes for OOP (you can read more from the book Object-Oriented JavaScript by Stoyan Stefanov).

Note: From now on, for easier to understand the pattern, I’ll call all constructor functions (that are capitalized in examples) classes; don’t be confused.

First, we’ll mimic above example by creating  Animal and Elephant classes as follows:

// parent class
function Animal(){
    this.name = "Animal";	
}
// parent’s properties
Animal.prototype.getName = function(){
    return this.name;
};
Animal.prototype.setName = function(name){
    this.name = name;
};
 
// child class
function Elephant(){}

YUI 3 supports class inheritance via oop module and because this is used widely by almost all other modules, you’ll rarely have to include it explicitly. However, for testing, just call Y.extend() method within oop’s scope (that let Elephant inherit Animal as you can guess):

YUI().use('oop', function(Y){
    Y.extend(Elephant, Animal);
 
    // test code here
    // ...
}

Next we’ll do some tests:

// create an object of Elephant
var jumbo = new Elephant();
 
alert(typeof(jumbo.name)); // undefined
alert(typeof(jumbo.getName)); // function
 
// set name for the Elephant object			
jumbo.setName("Jumbo");
alert(jumbo.getName()); // Jumbo

You can see from the example, jumbo object which is an instance of Elephant class only inherit members of the prototype, not “private” members from parent’s class and it is considered a good practice to leave all instance-specific properties as private properties and to add all the public functionality to the prototype.

Interestingly we can add some new properties with default values to child class via arguments of Y.extend(), for example, to add trunk and tusks to Elephant class:

// create an object of Elephant “class”
var jumbo = new Elephant();
 
alert(typeof(jumbo.name)); // undefined
alert(typeof(jumbo.getName)); // function
 
// set name for the elephant				
jumbo.setName("Jumbo");
alert(jumbo.getName()); // Jumbo

Last but not least, class inheritance has very powerful feature: superclass access. To see how it works, we’ll add a method to Animal class to let it say something.

// parent class
function Animal(){}
 
// parent’s method
Animal.prototype.say = function(){
    return "I am an animal.";
};

Then, we’ll overwrite say method in Elephant class, yet still be able to keep what Animal can say about.

Y.extend(Elephant, Animal, {trunk: 1, tusks: 2});
 
Elephant.prototype.say = function(){
    	  return Elephant.superclass.say() + 
		" I have " + this.trunk + " trunk and " + this.tusks + " tusks.";
};
 
// test
jumbo = new Elephant();
alert(jumbo.say()); // I am an animal. I have 1 trunk and 2 tusks.

In summary, “class” inheritance pattern in YUI 3 is more powerful than prototypal counterpart though harder to get it full, here are some important points:

  1. YUI 3 allows us to implement inheritance at (pseudo) class level in JavaScript.
  2. Inherited classes cannot directly access to parent’s own members, children only inherit prototype members by default.

    Note: Well, it is possible to inherit parent’s own properties by initializing the parent constructor from the child (but it is not always a good OOP practice). See example:

    // parent class
    function Animal(){
        this.name = "Animal";	
    }
    // child class
    function Elephant() {
        // initialize the parent using the child as "this"
        Elephant.superclass.constructor.apply(this, arguments);
    }
     
    Y.extend(Elephant, Animal);
     
    // test
    jumbo = new Elephant();
    alert(jumbo.name); // Animal
  3. You can gain access to the parent’s overridden methods via superclass.

Conclusion

Code reuse is considered as the most confusing part of JavaScript for it lacks robust OOP features that many modern programming languages provide by default. YUI 3 with the two inheritance patterns we’ve gone through is trying to fill the gap.

Prototypal inheritance is easier to understand but limit in object inheritance only. To get full OO support in YUI 3, it is advisable to study “class” inheritance pattern provided by the framework.

Why Do We Need Google Closure?

3

Posted on : 01/04/2010 | By : Jimmy Vu | In : Development News

Why Google Closure?

When a new JavaScript library arrives, a question is often raised reasonably: “Why does the world need another library?” while we’ve already had too many good ones like jQuery, Prototype, Mootools, YUI… you name it.

To find the right answer, just have a look at the package offered by Google under the name of Closure project. We’ll find there three sub-projects:

  1. Closure Compiler: a JavaScript optimizer. This is not a “yet another JavaScript compressor”, it can do more: Besides compressing your codes it can analyze your code and remove “dead” parts, correct wrong syntax, check variable references/types, warn about common pitfalls. The really good news is it comes with a Firebug extension, called Closure Inspector, that allows us to debug compressed code by linking obfuscated lines to original ones.
  2. Closure Library: a JavaScript library (as we expect) intended for use with  Closure Compiler. Basically it can do all the common tasks like other libs such as DOM manipulation, server communication, animation/effect and encloses a large set of reusable UI widgets and controls.
  3. Closure Templates: is not just a client-side JavaScript template engine like Pure but can be used in server-side with Java.

Closure Library is a big library with more than 400 JavaScript files well organized into Java-like directory structure. We’ll find there something like packages, classes/sub-classes with Java-doc syntax description (in fact, you know, there are no true packages/classes in JavaScript.)

Best IE6 “PNG Alpha-Transparency” Fixes

4

Posted on : 12/27/2009 | By : Jimmy Vu | In : Solution

You are likely living in civilized society with Firefox, Safari, Chrome or Internet Explorer 7/8 installed in your computers. Yet, some are still in the dark with the older Microsoft browsers named Internet Explorer 6 (IE6) or, worse, older versions. One of the most painful facts about IE6 is that it does not natively support PNG alpha-channel transparency.

Microsoft probably thought that GIF transparency — where each pixel is either fully transparent or a solid color, not anything between — should be enough for the world. But it’s not! Just compare three “JavaScriptly” logos in transparent GIF, transparent PNG and semi-transparent PNG images on a web page, you’ll recognize the differences.

Transparent PNG vs Transparent GIF

Transparent PNG vs Transparent GIF

(1) The font edge of GIF logo has side-effect which can be only fixed by choosing “color matte” exactly like background color when exporting the image (but we can do nothing optimal if the background has multi-colors like a picture.)

(2) Only PNG can be semi-transparent like the last logo, GIF is out of luck.

Something for Christmas: Snowfall in Picture

0

Posted on : 12/23/2009 | By : Jimmy Vu | In : Misc, jQuery

Now it is time for Christmas and if you want to add some snows to a picture like the below example, a cool jQuery plugin — created by Jason Brown — can come to help.

corMVC: An jQuery-based MVC Framework

5

Posted on : 12/22/2009 | By : Jimmy Vu | In : Solution, jQuery

I know quite a few JavaScript MVC frameworks out there but corMVC is what makes me exited at most for a few reasons.

corMVC stands for “client-only-required” Model-View-Controller and that means it does not depend on specific server-side technology. In case you want to demo something, it would be perfect if everything can be done on client side. Of course, you can save changes or load data from server (via Model) as the general illustration below.

corMVC Overview

corMVC Overview

Not like other JavaScript MVC solutions, corMVC is very simple and has very small footprint. It also does not require you to build the application using scaffolding or any other command-line utilities.

FireQuery – An Introduction

0

Posted on : 12/20/2009 | By : Jimmy Vu | In : jQuery

Installation

FireQuery is an extension of Firebug created by BinaryAge to help developers to keep track with jQuery expressions, data and collections as expressed on tool website:

  • Query expressions are intelligently presented in Firebug Console and DOM inspector
  • attached jQuery data are first class citizens
  • elements in jQuery collections are highlighted on hover
  • jQuerify: enables you to inject jQuery into any web page

You can install the tool from official Mozilla add-on page (it requires Firebug 1.3+ already existed.) One note: You may have to find an older version (v0.3) to make it work with current official Firebug release (v1.4) as my experience on Windows.

In Action

After installing the add-on and restarting Firefox, just go to the test page to see how FireQuery tracks embedded jQuery data on FireBug’s “HTML” tab. The image below illustrates the data embedded in accordance with the jQuery codes to inject them to the page.

jQuery Code Content Assistance for Eclipse WTP

13

Posted on : 10/13/2008 | By : Jimmy Vu | In : jQuery

JavaScript code content assistance built in Eclipse WTP does very good job that I found even better than the same functionality in some commercial solutions, however, jQuery’s syntax is not supported (no surprise). That’s why jQueryWTP tool comes to help adding jQuery support to Eclipse WTP (and Eclipse PDT, MyEclipse which are based on WTP too.)

This is not an Eclipse plugin instead a tool to patch the existing plugin and inject jQuery’s syntax support into it. First download the tool from SourceForce; it’s a Java executable JAR so you can double-click to it or run it from command line:

java -jar jqueryWTP0.2forJQuery1.2.6.jar

Now browse to plugin file

org.eclipse.wst.javascript.ui_xxxxxxx.jar

and set output directory to generate the patch. Please backup the original file and set output directory different from source one.

 

jquery-eclipse-wtp-ui.gif

 

Select “Generate” button to get the patched file then copy over original file. Start Eclipse and open a HTML or script file to see jQuery’s functions listed on code assistance like image below.

Simple Web Chat with Meteor Comet Server

8

Posted on : 09/19/2008 | By : Jimmy Vu | In : Solution

Comet is not really brand-new (Ajax) term today; however, with most of people how it works remains somewhat mysterious.

I have a little hand-on experience with Comet when creating a hobby game project with DWR Reverse Ajax sometime ago. It (DWR) was simple to start and really worked but required a Java web server (Tomcat, Jetty…) that I found rather expensive (in term of resources) for such small application. I want a small, dedicated and reliable server for Comet apps while don’t like to be deeply sunk in technical terms like “Bayeux” or “Continuation”.

After reviewing the Comet Maturity Guide from Comet Daily I decided to give Meteor Comet server a try for several reasons, especially because it’s built on Perl that can be easily deployed in any server with Perl installed (i.e. almost all Linux servers, no?) and it should be lightweight (up to my experience with Perl). Here is other info about Meteor server:

  1. Server daemon will run on any platform for which Perl is available.
  2. In live use typically 1,000 clients per node receiving 2 msgs (~400 bytes) per sec each. Tested up to 5,000 clients per node receiving 1 msg/sec each.
  3. Nodes exist independently, supports broadcasting for message distribution. Cluster of three Meteor nodes runs FT Alphaville.
  4. Transports are completely configurable within simple constraints.
  5. Server supports client ‘catch-up’, allowing clients to regulate quality of service themselves.
  6. Stable, in production use.
  7. GPL v2. Free.

Install & Setup Meteor Server

You can find very good how-to guide for installing Meteor server from Meteorserver.org; actually it’s quite simple to follow. Just download, extract to default location (/usr/local/meteor) and configure daemon service as guided. One notice is on Fedora/Cent OS the start function in init scripts must be changed from:

Quick & Useful jQuery Plugins

1

Posted on : 09/16/2008 | By : Jimmy Vu | In : Solution

Here are some quick and useful jQuery plugins from Jason Frame’s “jQuery Grab Bag“.

Auto-Grow TextArea

The technique is borrowed from Facebook that uses an off-screen <div> to calculate the required dimensions of the textarea to reveal all texts inside instead of to display vertical scrollbar. Run the following code line to enable auto-grow behavior to all textareas on page.

$('textarea').autogrow();

Online Demo

Input Hint

It’s not always necessary to attach label to every text field in web form, instead you can use hint to tell user what to type in the fields. This plugin will help keeping away from tedious codes to add hints to input boxes.

First, add hint attribute to input fields.

Unobtrusive Draggable Tabbed Navigation

3

Posted on : 09/15/2008 | By : Jimmy Vu | In : Solution

There are many examples on creating tabbed navigation with (or without) help of JavaScript frameworks like Prototype, MooTools or JQuery. However, I find that it’s much easier to create draggable tabbed navigation using Chain.js and its great extension: Interaction.js.

Riziq, creator of Chain.js & Interaction.js, already showed an example on how to utilize the libs to build tab interface in a few JS code lines. However, for its own purpose, the example is not SEO-friendly — disabling JavaScript in your browser will result in empty content and search engines will see nothing on your page consequently. Now say, you want to create a tabbed navigation for your blog to show/hide “Latest Posts”, “Latest Comments” etc. and you want the links can be seen no matter if JavaScript is enabled or not in reader’s browser — something looks like this:

Tabbed navigation for my blog

Blog's tabbed navigation

Step 1: HTML & CSS

Just create a template in HTML and full links to latest posts, comments and most popular articles: