views:

145

answers:

8

We are attempting to only make available certain functions to be run based on what request address is.

I was wondering how we could do this:

if(condition1) 
{
    $(document).ready(function() {
        ...
        ... 
        // condition1's function
    });
}
else if(condition2) 
{
    $(document).ready(function() {
        ...
        ... 
        // condition2's function
    });
else if...

I was wondering what a good pattern would work for this? since we have all of our functions in one file.

+1  A: 

I don't see any problem with that. But this might be better:

$(document).ready(function() {
    if (condition1) 
       // condition1's function
    else if (condition2)
       // condition2's function
    ...
});
Buu Nguyen
A: 

Maybe you could give more detail as to what exactly you are doing, but from what I can tell why wouldn't you just make a different JS file containing the necessary functions for each page instead of trying to dump all of them into one file.

Corey Sunwold
My guess is if they always include the same file it gets cached. And they don't have to worry about maintenance issues (the same function in multiple files).
Nosredna
+4  A: 

It depends on what your conditions are like...

If they're all of a similar format you could do something like

array = [
    ["page1", page1func],
    ["page2", page2func],
    ...
]

for(i=0; i<array.length; ++i)
{
    item = array[i];
    if(pageName == item[0]) $(document).ready(item[1]);
}
Nick
@Nick: +1. This is the best approach out of all that I've seen, although I might use a hash table approach.
Grant Wagner
The benefit of this approach over a hash table is that you can use a partial match for the condition that matches 'pageName'. For example: 'if (item[0].indexOf(pageName) == 0) { ...' or 'if (item[0].test(pageName)) { ...' (in this example, item[0] is a regexp, not a string).
Grant Wagner
A: 

I would just leave all of the functions in one file if that's the way they already are. That will save you time in rework, and save the user time with reduced latency costs and browser caching. Just don't let that file get too large. Debugging and modifying will become horrendous.

If you keep them all in one file, Add a script onn each page that calls the one(s) you want.

function funcForPage1() {...}

function funcForPage2() {...}

Then, on page1

$(funcForPage1);

etc.

geowa4
@George: I think you mean $(document).ready(funcForPage1);
Grant Wagner
+3  A: 

I like Nick's answer the best, but I might take a hash table approach, assuming the 'request address' is a known fixed value:

var request_addresses = {
    'request_address_1': requestAddress1Func,
    'request_address_2': requestAddress2Func
};

$(document).ready(request_addresses[the_request_address]);

Of course, request_addresses could look like this as well:

var request_addresses = {
    'request_address_1': function () {
        /* $(document).ready() tasks for request_address_1 */
    },
    'request_address_2': function () {
        /* $(document).ready() tasks for request_address_2 */
    }
};
Grant Wagner
The addresses would need to be matched via regex.
LB
@LB: If you need to match the request addresses using regex use Nick's solution, but change the 'item[0]' values to be regex and the condition to be 'if (item[0].test(requestAddress)) { ...' (or you can use String.match()).
Grant Wagner
awesome Grant, thanks!
LB
+1  A: 

It would probably be cleaner to do the site URL checking on the server (if you can?) and include different .js files depending on the condition, e.g.

** Using ASP.NET MVC

<html>
<head>
  <%
  if(Request.Url.Host == "domain.com")
  { %><script type="text/javascript" src="/somejsfile1.js"></script><% }
  else
  { %><script type="text/javascript" src="/somejsfile2.js"></script><% }
  %>
</head>
</html>

This way, each js file would be stand-alone, and also your HTML wouldn't include lines of JS it doesn't need (i.e. code meant for "other" sites)

JonoW
That would hurt his caching. It would also mean having the same function in multiple source files. Of course, that could be fixed with some fancy build-work.
Nosredna
Either way, he'll have to deal with caching issues since he'll be pulling the Request url via asp.net
Allen
Allen, I don't know anything about asp.net. Can you give me a quick education on why?
Nosredna
A: 

Instead of doing what you're planning, consider grouping the functions in some logical manner and namespace the groups.

You'd have an object that holds objects that holds functions and call like this:

serial = myApp.common.getSerialNumber(year,month);
model = myApp.common.getModelNumber(year);

or

myApp.effects.blinkText(textId);

If you wanted to hide a function or functions per page, I suppose you could null them out by function or group after the load. But hopefully having things organized would satisfy your desire to clean up the global namespace.

Nosredna
A: 

I can't think of a particularly elegant way to achieve this using only JavaScript. If that's all that's available to you, then I'd at least recommend you use a switch statement or (preferably) a hash table implementation to reference your functions.

If I had to do something like this, given my development environment is fully under my control, I'd break up the JavaScript into individual files and then, having determined the request, I would use server side code to build a custom bundled JavaScript file and serve that. You can create cache copies of these files on the server and send client side caching headers too.

This article, which covers this technique as part of a series may be of interest to you.

Kieran Hall
That's pretty interesting. Still, I think the advantage of having just one js file is compelling on a site with many pages. You serve it once and only once. And you don't have the build complexity or the server complexity to worry about. It's all going to depend on the size of the js file and the number of expected pages that will be served, I guess.
Nosredna