Identical functions in multiple loaded scripts - choosing which version is called

I've got a single page for editing various sets of data; the user chooses which set to work with from a menu, and the page loads the list of stuff & textboxes, etc, into a container div on that page via xmlhttp. There is one universal "save" button that simply calls "save()".

Each editing module has its own .js file with native functions and a "save()" function defined. Since the content & scripts are loaded dynamically, if the user chooses 3 or 4 different options, each of those .js files gets loaded and the "save" functions keep getting overwritten. Since javascript uses the last defined version of a function this causes problems if they go back to a previously loaded module.

So basically my question is, how can I reload or reposition scripts in such a way that an already-loaded script's function becomes the "last defined" version of that function?

Here's a pseudocode example:

function loadScript(filename)
  if(document.scripts[filename]) return, else document.scripts += new script(filename)

function onMenuChange(newModule)
since each module has its own "save" function, this happens

onMenuChange(moduleA) // calls the "Save" function from moduleB.js
Who is Participating?
Jens FiedererTest Developer/ValidatorCommented:
You could have the event handlers call a function that uses a global object.  This global object would contain whatever you want to be the "last defined" object, and the handler could call g_functions.Save()
Jens FiedererTest Developer/ValidatorCommented:
One solution is NOT to use globally scoped save functions.

If you make the Save function a method of an object (or methods of several objects), then multiple Save functions
can coexist.

You can then call either


depending on which is appropriate.
noamattdAuthor Commented:
I thought about that.  I'm doing this with .NET and each module is a composite server control, as is the universal save button (and other buttons with similar features); the goal being to generate the universal buttons once, and not have to mess with them any more.

If I were to have save be the method of different objects I would have to change the event handlers for each button every time a new module was loaded, and I was hoping to avoid that.
noamattdAuthor Commented:
That sounds more like what I had in mind, could you give an example?
noamattdAuthor Commented:
Never mind, I got it.  Thanks a bunch.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.