views:

56

answers:

3

Maybe a closure is my solution? Not exactly sure how to pull it off though.

The code is set up like so:

var globalVar = '';
var globalVar2 = '';

function func()
{
   if (condition)
     func2(globalVar) 
   else 
     func2(globalVar2)
}

In func2() I cache some HTML in a main container into the appropriate global variable that I pass to it. Basically I have a main container that holds different pages depending on what tab they choose. For performance I want to cache the page into global vars so I need to know what tab is active to figure out which global var to assign the HTML to.

A: 

The way you've done it will work just fine. However, you're not really passing the reference to a string, you're binding the global variables into your closure. Do you have a more specific question? Does your code not work?

Matt Ball
that's why i posted the question. it doesn't work. if you pass in the global variable u pass in the contents right? i don't want that. i want to pass in a ref to the global var so i can take the main container HTML and assign it to the right global variable.
ijjo
A: 

Might I suggest simply adding these cached pages to the dom and hiding them using CSS rather than trying to hold onto them in JS and constantly change the main content container?

aepheus
That's not really necessary either. I would just use AJAX and load the pages from file.
dclowd9901
But, then you would be having a new httprequest every time you changed content, which is what caching prevents. This way you would at most load each page once. Your way you could load the pages infinitely many times. A bit of an exaggeration, but you get the point.
aepheus
the main container is loaded via ajax when someone clicks on a tab. at that moment i cache the main container html, put a ajax loader animated gif then make an ajax call to the server. when the call returns i load that html into the main container. i don't want to have to hit the server with an ajax request every time someone tabs back and forth. so it's one call, then cached on every next tab click. to cache all the pages in the dom and hide them would be a bad idea. i'd have to load all 6 tab contents on the page load, which is not needed.
ijjo
Just load them as they are called, not on page load. Initially you would load just one. Then as the person tabs around, rather than caching in javascript, cache in the dom (hiding the containing dom element), that way you don't have to add the cached content back to the dom, you can just reveal it.
aepheus
+1  A: 

as globals are just properties of the window object in javascript, just pass "globalVar" or "globalVar2" and assign it using window[myvar] = ...

mihi
cool. that'll work. thanks
ijjo