There is a clever way -- in John Resig's book he talks about it -- it
involves executing the anonymous function right after declaring it, when in
a for loop:
function() { do whatever; }();
But, I tried some experiments and I couldn't get it to work right.
-- Josh
I ended up doing something similar to what you suggest, but I really
was hoping to elicit some clever way to get the value of the variable
at the time of the assignment, rather than the "5" that I get because
the closure is maintaining the context.
Is there a way to set these event handlers up in jQuery without using
a closure?
--T
On Jan 30, 4:36 pm, "Josh Nathanson" <[EMAIL PROTECTED]> wrote:
Instead of binding five times, you can do it dynamically:
$("[id^=port]").click(function() {
bigchart( this.id.charAt(this.id.length-1) );
});
Something close to that should do it. Although if you end up with 10 or
more clickables you'll have to change your naming scheme a bit.
-- Josh
----- Original Message -----
From: "timothytoe" <[EMAIL PROTECTED]>
To: "jQuery (English)" <jquery-en@googlegroups.com>
Sent: Wednesday, January 30, 2008 12:10 PM
Subject: [jQuery] Fighting a closure
> I think I submitted a half-done version of this message by accident a
> few minutes ago. Sorry.
> This works:
> $("#port0").click(function() {bigchart(0)});
> $("#port1").click(function() {bigchart(1)});
> $("#port2").click(function() {bigchart(2)});
> $("#port3").click(function() {bigchart(3)});
> $("#port4").click(function() {bigchart(4)});
> I try to roll it up like this:
> for (i=0;i<5;i++) {
> $("#port"+i).click(function() {bigchart(i)});
> }
> But the closure gets me. When the function is called, i is 5 for any
> of the buttons.
> What is the elegant solution here?