Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

JavaScript Item Framework

3.33/5 (2 votes)
18 May 2010CPOL 10.9K  
Helps simplify JavaScript when using ASP.NET and iNamingContainer.

Introduction

This article will cover the item management part of the framework.

Background

After inheriting an ASP.NET project which implements master pages, I was getting frustrated by having to request client IDs using server-side includes. Some developments require heavy DHTML, and the following made accessing server rendered controls a lot easier when using the iNamingContainer.

The Code

The following is the code for the item framework:

JavaScript
var ctlHolder = function(id, ctl) {
  this.ID = id;
  this.Ctl = ctl;
}

var ctlDef = function() {
  this.Items = new Array();
  this.Add = function(item) { this.Items[this.Items.length] = item; };
  this.Get = function(id) {
    for (var obj in this.Items)
      if (this.Items[obj].ID == id)
        return this.Items[obj].Ctl;
    return null;
  }
  this.EndID = function(id) {
  var index = id.lastIndexOf('$');

  if (index == -1)
    return id;
  else
    return id.substring(index + 1);
  }
}

var ctl = new ctlDef();

function catalogItems(items) {
  if (items == null) items = document.getElementsByTagName('html');
  for (var obj in items) {
    var item = items[obj];
    if (item.id)
      ctl.Add(new ctlHolder(ctl.EndID(item.id), item));
    if (item.childNodes)
      catalogItems(item.childNodes);
  }
}

The "catalogItems" function needs to be called when the page loads. This can be achieved by adding the following attribute to the body element:

JavaScript
onload="catalogItems(null);"

This code runs very quickly parsing and cataloging, rendering 300K HTML in 0.1 seconds. Once this is completed, you can replace complex element references such as:

JavaScript
document.getElementById('ctl_001$ctl_content1$txtUsername')

with:

JavaScript
ctl.Get('txtUsername');

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)