Friday, October 30, 2009

[jQuery] Re: How to prevent default behavior in an event handler that returns a function

Hi risteli!

The problem I'm having is not with the "i" iterator variable but with
passing an event into the handling function.

The code I used to handle the "i" iterator issue is essentially like a
closure, I think. Instead of defining the function right in the event
assignment, though, I define it elsewhere in another function that
simply returns it.

Thanks!

-Nathaniel

On Oct 29, 2:16 pm, risteli <rist...@gmail.com> wrote:
> Hello,
>
> this is one of the possible generic ways to do it using closures:
>
>         for (var i=0;i<whatever;i++) {
>                 (function() {
>                         var my_i = i;
>                         $("#something").click(function(){ do_it(my_i)});
>                 })();
>         }
>
> depending on your real code, it can surely be written in better ways.
>
> On Oct 29, 5:29 pm, The alMIGHTY N <natle...@yahoo.com> wrote:
>
> > Example page:http://jqueryfun.nathanielklee.com/eventFirefox.html
>
> > Following one example provided in an official jQuery tutorial (located
> > athttp://docs.jquery.com/Tutorials:How_jQuery_Works), I can pass
> > "event" into a function I define directly in the click assignment
> > handler.
>
> > e.g. $("#something").click(function(event) { event.preventDefault
> > (); });
>
> > However, if this is put into a for loop and modified to include a
> > statement that requires a value of i from the for loop iteration, it
> > won't work because when the handler is fired, it only knows the last
> > iterative value of i.
>
> > I get around that by instead making a call to a function that returns
> > a function that executes the statements I want.
>
> > e.g. $("#something").click(doSomething(i)); function doSomething(i)
> > { return function() { alert(i) }; }
>
> > So far, so good.
>
> > The problem I run into is that I need to prevent the default behavior
> > with event.preventDefault(). Browsers won't recognize if I pass
> > "event" into the function even though the aforementioned tutorial
> > indicates that one can indeed pass "event" into a function. How can I
> > get around this problem?
>
> > I realize that there are other ways I could do the same thing, such as
> > applying a class to the links in question and referencing the event
> > target (example below), but I'm interested in figuring out why the
> > method I described above doesn't work and whether there's a way to get
> > it to work.
>
> > e.g. $("#something").click(doSomething); function doSomething(event)
> > { alert($(event.target).attr("anAttribute")); }
>
> > Thanks!

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate