>
Blog
Book
Portfolio
Search

3/5/2008

2908 Views // 0 Comments // Not Rated

Listen JavaScript... I Need Some (Function) Closure To Our Relationship

I am working on what I call the "TreeJAX" control. It a tree that is bound to a hierarchical collection of objects. The root node is built in code on the control's load method. Then, whenever a node is clicked, I use ASP.NET AJAX JSON asynchronous web services to dynamically build the children all from client script.

Basically, I have something like this:

Code Listing 1

  1. function SomeJavaScriptAsyncCallbackMethod(asyncResults)
  2. {
  3. for (var n = 0; n < asyncResults.length; n++)
  4. {
  5. var businessObject = asyncResults;
  6. SomeNormalJavascriptMethod(businessObject);
  7. }
  8. }
  9. function SomeNormalJavascriptMethod(bo)
  10. {
  11. var table = $get('<% = this.tblTree.ClientID %>');
  12. for (var n = 0; n < table.rows.length; n++)
  13. {
  14. ...
  15. }
  16. ...
  17. }

The table was infinitely looping! Changing the name of my iterator in the first method from n to, say, m made it work! The problem with this code, like so many of my ex-girlfriends, is closure. Closures are functions that "inherit" their environment (ie, in-scope variables) in which they are declared.

In .NET (C# 2.0 and beyond), this idea is seen in anonymous delegates. Normal methods are not closures; they are, however, in JavaScript. But we all know this, right? Well, the only reason I went through this is because all of the examples I've seen of explicit closure in JavaScript is with anonymous functions declared inside of other functions. It looks like this is also the case then you call a "normal" method from another.

So don't blame JSON or AJAX or any other fancy script technology for your scripting woes (like I did initially). JavaScript is JavaScript, and most of us haven't even scratched the surface. So this is just a heads up as to how closures work client side...

6 Tags

No Files

No Thoughts

Your Thoughts?

You need to login with Twitter to share a Thought on this post.


Loading...