Also interesting

Error. Page cannot be displayed. Please contact your service provider for more details. (19)


Link of the day - Free Macbook Air

 

JavaScript Recommendations for AJAX Component Writers

how to use different aspects of JavaScript

Use JavaScript Programming Conventions

Like with Java having a standardize style makes code easy to work with and maintain especially in larger organizations. The folks over at Dojo have a great set of JavaScript Programming Conventions.

Use object oriented JavaScript

Believe it or not you can write JavaScript in an object oriented way. Doing so will allow for better reusable code, enabling your objects to be organized and allow for dynamic loading or objects. The following is a JavaScript version of a shopping cart followed by equivalent Java code.

 function Cart() {
    this.items = [];
 }
 
 function Item (id,name,desc,price)) {
        this.id = id;
        this.name = name;
        this.desc = desc;
        this.price = price;
 }
 
 // Create an instance of the cart and add an item
 var cart = new Cart();
 cart.items.push(new Item("id-1","paper","something you write on",5));
 cart.items.push(new Item("id-1","Pen", "Something you write with", 3);
 var total;
 while (var l; l < cart.items.length; l++) {
     total = total + cart.items[l].price;
 }
 

The Cart object above provides basic support for maintaining an internal array of Item objects. The equivalent Java object representation of a cart may look as follows.

 import java.util.*;
 
 public class Cart {
   private ArrayList items = new ArrayList();
   public ArrayList getItems() {
       return items;
   }
 }
 public class Item  {
   private String id;
   private String name;
   private String desc;
   private double price;
	  
   public Item (String id, String name, String desc, double price) {
      this.id = id;
      this.name = name;
      this.desc = desc;
      this.price = price;
    }
    
    public String getId() {return id;}
    public String getName() {return name;}
    public String getDesc() {return desc;}
    public float getPrice() {return price;}
 }

The example above represents a server-side object representation of a cart. This object would need to be kept in the HttpSession by a JSP, Servlet, or JSF managed bean. AJAX interactions could be used to add Items to the Cart or retrieve the current state.

Use object hierarchies to organize JavaScript objects

In JavaScript there is the potential for object names to collide. In Java package names are used to prevent naming collisions. JavaScript does not provide package names like Java however you can. When writing components use objects and object hierarchies to organize related objects and prevent naming collision. The example below creates a top level object BLUEPRINTS which acts in a sense like a namespace for related objects. The objects are set as properties of the parent object.

 // create the base BLUEPRINTS object if it does not exist.
 if (!BLUEPRINTS) { 
     var BLUEPRINTS = new Object();
 }
 BLUEPRINTS.Cart = function () {
    this.items = [];

    this.addItem = function(id) {
        items.push(new Item(id);
    }
	
    function Item (id,qty) {
        this.id = id;
        this.qty = qty;
    } 
 }
 //  create an instance of the cart and add an item
 var cart = new BLUEPRINTS.Cart();
 cart.addItem("id-1",5);
 

This technique will prevent naming collisions and is a good practice if your code will be used where there is the potential of a naming collision.

Use the protoype property to define shared behavior and to extend objects

The prototype property is a language feature of JavaScript. The property is available on all objects. Property resolution in JavaScript is designed to look at the value the prototype property if a property is not found in the current object. If the value of the object defined as the protoype object does not contain the property the value of its prototype property is examined. Prototype property chains (hierarchies) are often used to provide inheritance in JavaScript objects. The following example will show how we can add behavior to an existing object using the prototype property.

 function Cart() {
    this.items = [];
 }
 
 function Item (id,name,desc,price)) {
        this.id = id;
        this.name = name;
        this.desc = desc;
        this.price = price;
 }

 function SmartCart() {
    this.total;
 }
 SmartCart.prototype = new Cart();
 

SmartCart extends the Cart object inheriting its properties and adds a total property. Next we will some convenience functions to the Cart that will allow items to be added and the total to be calculated. While you could add the functions directly to the SmartCart object, this will result in a new function being created for each instance of the SmartCart. In JavaScript functions are objects so for object where there are many instances being created a shared instance of the behaviors would save resources. The following code declares a shared calcualteTotal and a addItem function and adds them as a property of the SmartCart prototype member.

 Cart.prototype.addItem = function(id,name,desc,price) {
        this.items.push(new Item(id,name,desc,price));
    }

 Cart.prototype.calculateTotal = function() {
     for (var l=0; l < this.items.length; l++) {
        this.total = this.total + this.items[l].price;
     }
     return this.total;
 }
 
 // Create an instance of the cart and add an item
 var cart = new SmartCart();
 cart.addItem("id-1","Paper", "Something you write on", 5);
 cart.addItem("id-1","Pen", "Soemthing you write with", 3);
 alert("total is: " + cart.calculateTotal());
 

As you can see extending an object is pretty simple. In this case there is a single instance of the calcualteTotal addItem functions are shared across all instances of the SmartCart object (similar to a static method in Java). Note that the scope of the items is still this.items even though the functions are declared separately from the SmartCart object. When the new protoype functions are executed they will be in the scope of the SmartCart object.

It is recommended to use the prototype property to define shared behavior when there may be many instances of the objects as it will reduce the number of objects in JavaScript and its use provides a good separation of behavior from data. The prototype property is also ideal for providing defaults for objects (which is not discussed here). There is much more that can be done with the prototype property beyond the scope of this document. See the Resources section of this document for more information.

JavaScript Recommendations for AJAX, part II >>

Shop Bigger Bras