Skip to: Site menu | Main content

Welcome to JasonHolden.com

Here you'll find information about my work and services.

Blog...

Extending a Yahoo UI widget.

Recently, I had the need to determine if a YAHOO.widget.TextNode with a specific label existed within a parent node, also an instance of YAHOO.widget.TextNode. I decided to create a custom YAHOO.widget.TextNode by extending the class. This is the first time I've tried to use any OO javascript. I was quite pleased with how easy I could extend any class. Thanks mostly to the excellent documentation provided by Yahoo.

Here's how I did it:

I started by creating node.js to hold my class definition:

I created a custom namespace "JTC.widget"

YAHOO.namespace("JTC.widget");

Create a constructor with the same signature as YAHOO.widget.TextNode and chain the superclass constructor.

YAHOO.JTC.widget.Node = function(oData, oParent, expanded) {
YAHOO.JTC.widget.Node.superclass.constructor.call(this, oData, oParent, expanded);
};

The YAHOO Global Object provides an extend() method to make extending objects within the library easier. The extend method effectively sets up the prototype, constructor, and superclass properties for objects that are extending other objects. This MUST be called immediately after the constructor of the custom object.

In this example our custom node (YAHOO.JTC.widget.Node) will extend YAHOO.widget.TextNode

The first parameter is the object that will extend the object in the second parameter. A third optional parameter can contain an object with custom properties and methods to be appended to the object that is passed into the first parameter.

YAHOO.lang.extend(YAHOO.JTC.widget.Node, YAHOO.widget.TextNode, {
   findNode: function(label) {
      if (this.hasChildren() && this.children.length > 0) {
         for (var counter = 0; counter < this.children.length; counter++) {
            if (this.children[counter].label == label) {
               return this.children[counter];
            }
         }
      }
   
      return null;
},

   childExists: function(label) {
      var node = this.findNode(label);
         
      if (YAHOO.lang.isNull(node)) {
         return false;
      } else {
         return true;
      }
}
});

In this example I've created and inline object with the custom methods I wish to implement.

Remember to include node.js in your page.

Now rather than calling the stock TextNode object:

var node = new YAHOO.widget.TextNode(data,parent,expanded);

create the custom node object

var node = new YAHOO.JTC.widget.Node(data,parent,expanded);
if (node.childExists("Child 1") {
alert("Child 1 exists!");
} else {
alert("Child 1 does not exist!");
}



SOURCE: node.js

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
BlogCFC was created by Raymond Camden. This blog is running version 5.7.002.