in

ASP.NET Weblogs

Andy Smith's Blog

Page.RegisterStartupScript('Andy', 'MetaBuilders_WebControls_GainKnowledge();');

all script techniques have a drawback

It turns out that the object intialiser javascript technique that I've been raving about has a downside, in that it's only defined in ecmascript v1.2+. For those of you not up on your ecmascript history, that's v4 browser era.

This wouldn't be _that_ bad if I didn't want to use it in the Array Declaration area of asp.net. This area doesn't let you use script to determine browser support. It's declarative by nature. So if it gets emited to an older browser, I get a nasty bad syntax error with no way to get around it. Not only that, but it would probably disrupt every other script on the page, because all asp.net array declarations go in the same script block.

So, to keep my nice syntax ( no magic numbers! ) in the library area of the script, I have to do something else for older browsers.

What you can do is check the script version server side, and emit something like the following function for v1.1- browsers:

function MetaBuilders_Initialiser() {
  for( var i = 0; i < arguments.length; i = i + 2 ) {
    this[ arguments[ i ] ] = arguments[ i + 1 ];
  }
  return this;
}

then change the array declaration to call it like this:

var Foos = new Array( new MetaBuilders_Initialiser('FirstName','Andy','LastName','Smith') , new MetaBuilders_Initialiser('FirstName','Jon','LastName','Doe') );

For script version 1.2+ browsers, you can use the simpler syntax:

var Foos = new Array( { FirstName:'Andy', LastName:'Smith' }, { FirstName:'Jon', LastName:'Doe' } );

The two have the same result. With this branch in logic at the array level, you can support simple objects in the Init function so you don't have to deal with array indexes. I'm not sure if i'm going to do this or just go back to my old ways. But I just wanted to let everybody know my findings.

Comments

 

Cadmium said:

Unless you are working on a really critical app that absolutely has to be seen by everyone (say a government site), I wouldn't even bother. The number of people using browsers earlier than 4x is well below 1% (4x browsers are at about 1%). And at that point, you're html is just as likely to break as your javascript.

To me it's not worth spending 50% of my time for 1% of the audience. You can't support every browser every created unless you compromise what you are doing to the point it looks and works poorly everywhere :)
September 24, 2003 10:40 AM
 

Dunc said:

Andy, no offence but I think you need a formal JavaScript education: http://www.amazon.com/o/ASIN/0596000480/
:-p
Honestly it's a great book for a great language.
September 26, 2003 4:10 AM

Leave a Comment

(required)  
(optional)
(required)  
Add