In my JS application, I am using AJAX to load different parts of the application. After the AJAX function is completed, the corresponding script is executed.
However, I am facing an issue when trying to load a new part of the application. I need to find a way to remove all events and variables associated with the previously loaded part of the app.
For instance:
$('#loadPart1').click(function(){
$.ajax({
url : url,
success : function(xhr){
// xhr contains JavaScript code to execute
// and events that need to be stopped afterwards
$('body').html(xhr);
});
});
// Loading another part of the app
// Should stop executing previous JavaScript
// and only run the newly loaded JavaScript from this AJAX call
$('#loadPart2').click(function(){
$.ajax({
url : url,
success : function(xhr){
// xhr contains JavaScript to execute
// and replaces the old script
$('body').html(xhr);
});
});
I hope this explanation makes sense. This is just sample code for illustration purposes, not my actual code. This is just to convey the problem I am facing.
When I load something via AJAX in my existing application, the events from previous scripts still continue to execute.
Is there a technique or pattern to prevent the execution of unwanted JavaScript? I want to remove all events without explicitly calling them.