0

I had this function:

function loadCollapse() {
  function collapseDetail() {
    $(this).next().fadeToggle(500);
  }    

  //toggle the componenet with class summary  
  $("span.summary").unbind('click',collapseDetail);
  $("span.summary").click(collapseDetail);
}

This function is bound to the ajaxComplete() event, aka gets executed whenever all ajax requests finish. The weird thing is that the unbind does not work.

It only works when collapseDetail() is defined/moved outside of loadCollapse(). Why?

Is a function inside a function really re-defined everytime that function get's executed?

Are there any potential memory/performance problems arising from this that i need to worry about?

1 Answer 1

4

Every time you call the function, the collapseDetail function will be redefined, thus it will be a different function from the one you created last time. Since it's a different function, and not the one you bound to at the first call, the unbind won't have any effect, because this new collapseDetail function was never bound.

Example of one way to solve this:

function generateLoadCollapse() {
    var collapseDetail = function() {
        $(this).next().fadeToggle(500);
    };

    var loadCollapse = function() {
        $("span.summary").unbind('click',collapseDetail);
        $("span.summary").click(collapseDetail);
    };

    return loadCollapse;
}

Another way could be something like:

function generateLoadCollapse() {
    return (function() {
        this.collapseDetail = function() {
            $(this).next().fadeToggle(500);
        };

        $("span.summary").unbind('click',this.collapseDetail);
        $("span.summary").click(this.collapseDetail);
    })();
}

You could then assign the value returned from this function to what you previously had for loadCollapse:

loadCollapse = generateLoadCollapse();
Sign up to request clarification or add additional context in comments.

9 Comments

Is there a way to circumvent this? like the static keyword would in other languages?
@GungFoo, there are many ways, depending on how you structured your code... But no, there is no static keyword.
I am glad that there are many ways. :) name 1 that keeps the function in its current scope but also static. D:
@GungFoo, you named one yourself, in the question... Move it outside, so it's the same function.
but what if i want/need a function to be member of the/a function?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.