Monday, May 18, 2009

Passing Objects to Javascript Functions

Shifting from WinForms programming to ASP.Net web development was not an easy transition for me. One of the most difficult things was dealing with Javascript for client-side work. The language is poorly typed and way too freeform for my taste. Hence, much of the example code I've seen often resembles a plate of spaghetti.

Now that I've adopted jQuery into my everyday work, building client-side code is a LOT easier but there are still direct challenges with Javascript that have to be overcome. Such a challenge presented itself to me recently.

As might be expected, I've found that many of the Javascript functions I build have applicability on many web pages. So naturally one wants to build them generically and move them to shared external Javascript files. To do this, parameters often have to be passed to a function. If the function is referenced by the setTimeout or setInterval methods and one or more of these parameters is an object rather than a simple value then it gets a little tricky.

Through a lot of trial & error, and with the help of developers on ASP.Net, I figured out how to do this. The key is to pass the IDs of the objects, as the objects themselves cannot be passed. Here's an example of passing a reference to a Telerik RadTreeView and a Hidden Variable:

As you can see in the first set of code, you must pass the ClientID of ASP.Net controls to the Javascript function. Then in the function itself you need to retrieve the object with methods like $find and $get.

No comments:

Post a Comment