I have a page with about 30 forms on it, for client management, but the forms are only called to the page when the user clicks to open a specific form. Part of the output is a jQuery.getScript()
function to load the source file for that particular form. When the form is saved or cancelled, the form slides up and is removed from the page.
I ran into a problem when opening the same form more than once on a single page load. The js source file was added to the dom each time the form was called via ajax, and thus, on subsequent save events, the save function was performed multiple times, once for each time the js source file had been loaded into the dom.
I found a solution, and checked to make sure it was encouraged to share a question/answer before I posted this. Seems it is. Solution below in my Answer.
Here's the solution I came up with, but perhaps someone has something even better. Shared for the sake of the community:
I declare a global variable in my topmost js file, outside of dom ready, like so:
LoadedScripts = [];
Then in my php function to call the script, I made it conditional, like so:
public static function load($path, $echo = false)
{
$js = '<script>';
$js .= 'if(LoadedScripts.indexOf("'.$path.'") == -1) { ';
$js .= 'jQuery.getScript("'.plugin_url_constant.'/lib/js/'.$path.'"); ';
$js .= 'LoadedScripts.push("'.$path.'"); ';
$js .= '}';
$js .= '</script>';
if($echo) echo $js;
else return $js;
}
Then in my ajax request, I include this at the top of the form being returned:
$output = my_prints_class::load('forms/clients/'.$this->form.'.js');
$output .= $this->displayform();
Obviously if you're getting this script tag via ajax, you don't want to echo it generally, but I added the option to the function for non-ajax purposes.