Search code examples
javascriptajaxprototypejs

check if a function exist after dynamically changing data (after an ajax call)


I have a function which executes on window load

<div id="removeItOnAjaxCall">
<script>
    foo = function() {
    // some stuff
    }
</script>
</div>

There is also an ajax call which can remove this function from the DOM like.

    new Ajax.Updater('chkboxpos, 'myscript.php', {
        onSuccess: function(response) {
            $('removeItOnAjaxCall').remove(); //now I don't have foo function in my DOM. but DOM think it is
        }
    });

Now if I make a call to this function I got an error

element is null
var method = element.tagName.toLowerCase();

because the DOM thinks it has that function defined but actually it doesn't have one. I hope I am making it more clear now.


Solution

  • You're confused about how <script> tags work. Once a script is encountered and parsed, any definitions inside it are never removed, even if the script tag, or its enclosing element, is removed. The only way a function could be undefined is by doing so explicitly, such as delete window.fun; or fun = null.

    Therefore, your concern is misplaced. There is no need to check if the function still exists--it does, no matter what elements you manipulated in your ajax handler. Why did you think the function would become undefined?

    The DOM is fundamentally separate from the JS namespace. Functions are not contained in the DOM; they are contained in the JS namespace. The DOM has no idea whatsoever about what functions might exist or not. Nothing you could posssibly do to the DOM could affect JS logic or data. Since functions do not exist in the DOM, they cannot be removed from the DOM. You say

    Now if I make a call to this function I got an error because the DOM thinks it has that function defined but actually it doesn't have one.

    With regard to your error:

    element is null
    var method = element.tagName.toLowerCase();
    

    this has nothing to do with the function foo. Since the element has been removed, it is null. You can't get the tagName of a non-existent element. You say you are "making a call to this function", but you're not making a call to that function. You are trying to get the tagName of an element, which is an entirely different thing.

    Having said that, it seems a bit odd to place a script tag within an element which is maybe going to be removed--why are you doing that?