About Me

My photo
Experienced Web Developer using C#, ASP Classic (VBScript) and ASP.NET, MySQL, T-SQL, and other SQL variants, JavaScript (W3Schools Certified and very well versed in jQuery and learning Dojo), and XML. Heavy interest in JavaScript, framework creation on various language platforms, and keeping up with the best industry-accepted practices.

Monday, December 14, 2009

How I replaced eval for dynamic initialization

So, I've been trying to steer clear of JavaScript eval() as much as possible ever since I learned how horribly inefficient it is.

On a recent project I did, titled "Shark Tank", I decided to create the application on the premise that there would be one "landing" page, and the rest would all happen via AJAX.

Well, I needed to have certain things happen on page initialization, and I try to keep my JS all in one spot at the top of the page, and not scattered throughout the page.

So, in my links table on my database, I had the columns "FriendlyName", "URL", "Initializer"

FriendlyName would display the friendly name, i.e. "Add a Lead", URL would be the actual url "add.asp", and the Initializer would be a string literal of the initialization function, which was housed somewhere in my namespace, i.e. "BAMPIT.Add.Initialize"

I started off trying to figure out how to do this without eval, but ran out of time on my deadline, so I just decided to go with eval in order to get the app out on time. Using eval on a string literal to call a function name isn't TOO bad, but I wanted to do this without eval.

So after thinking on it for a while, I came up with a way to do it 100% dynamically, and without eval.



I would personally add this to a namespace or change the function name to avoid potential conflicts with anything.

The function basically starts at the window object and drills down the namespace until it reaches the function you want to execute, and then executes the function.

As always, criticism and comments are always welcome.

No comments:

Post a Comment