2

Is there a way i can pass information into a nested function ? The problem is i want to use jQuery to animate an object being removed and then after have it remove the object from the dom. But theres no way to pass information into the nested function. I first though the bellow would work but no luck,

tab = this.tab //this.tab is a dom element
$(this.tab).effect('drop',null,null, function(tab)
{
     $(tab).remove()
})

People have suggested that i store the element in a global put this function is part of a class and there can be many objects which may call this function at the same time.

Thankyou!

1
  • Doesn't this inside the closure refer to the object being animated? jQuery is quite clever in setting context, try console.logging this inside the closure. Commented Jul 21, 2011 at 10:14

1 Answer 1

9

Using closures you should be able to simply do

var tab = this.tab
$(tab).effect('drop', null, null, function() { $(tab).remove(); });

Note that tab is defined outside the "nested function", but since JavaScript supports closures, the function can access variables defined in the same scope as itself. In other words, it'll be able to access tab. Also note that it's not this.tab, since this refers to the context in which the code is called.

Addendum: I'm not a jQuery-guy (weird, I know), but I'd imagine that the function you pass to effect() will be executed in the tab element's context (i.e. inside the function this refers to the tab element). If so, you could probably just do

$(this.tab).effect('drop', null, null, function() { $(this).remove(); });
Sign up to request clarification or add additional context in comments.

1 Comment

Thankyou for that ! JavaScripts scope does confuse me. Also im not normally a jQuery person, but when it comes to needing altra quick development the jQuery library is useful!

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.