Reputation: 1581
I have the following pages. Page A and page B.
Page A contains:
I then use an ajax call to load Page B HTML into page A and fire a function to initialise page B's javascript.
If I decide to remove Page B from Page A, I will also want clear all of the JavaScript functions that were also initialised when pageB was loaded?
Is there a way to clear JavaScript functions?
Upvotes: 0
Views: 1773
Reputation: 121
For the way you structured your code, you can simply "delete" the function initPageB_function and you should be golden, like so:
delete initPageB_function;
If you have to reload the content of pageB again into the page, then it's a different story, because you should re-bind the event handlers for your onclick events. At this point it's much way better to follow another approach:
Put the markup AND the javascript code that deals with the event handlers for pageB "into" pageB; this way, when you load pageB via Ajax you'll load also all the JS code that deals with that page; this is called delegation (and it makes perfect sense, cause your container - pageA - is not supposed to know what it is going to be loaded).
If you're using an helper library like jQuery, everything should be pretty simple:
somewhere in pageA, you define a spot for loading pageB content:
<div id='pageB'></div>
when you have to load it:
$('#pageB').load( 'http://url.for.pageB' );
As soon as the load progress, the JS code in pageB will be executed and you'll be golden :) To remove the content of the page you will simply empty the container:
$('#pageB').empty();
And the JS too will be gone. The next time you'll reload the page again, its own JS will be executed again. pretty simple and effective. :)
Upvotes: 0
Reputation: 74076
You can use separate namespaces in both pages. So, e.g., page A places all its JavaScript under window['pageA']
whereas page B uses window['pageB']
.
To unload all of the functions from page B you simply have to use
delete window['pageB'];
Beware, however, that this does not clear any handlers or references to the functions of page B. So if there are some left, this might lead to errors.
Upvotes: 4