Saturday, December 12, 2009

Re: [jQuery] Re: proper way

No, the two examples shouldn't work the same. They are both working exactly as expected.

Let me slightly rewrite each version in a more step-by-step fashion and you will see why. The first version is equivalent to:

$(function() {
   function handleClick() {
      clickFunction1();
    }
   $('a.link1').click( handleClick );
});

In this code, you are defining a function and then passing a reference to that function into the click() method. When the click event is triggered, your handleClick function will be called, and that in turn calls clickFunction1.

The second example is equivalent to:

$(function() {
    var result = clickFunction1();
    $('a.link1').click( result );
});

See the difference? This code calls clickFunction1() immediately. It then takes the *return value* from clickFunction1() and passes that into the click() method as the event handler. But your clickFunction1() probably doesn't return any value, does it? And it certainly doesn't return a *function* as its return value (although a function can return another function if you want it to).

Why does it work this way? Because you put the () after the clickFunction1 name. Whenever you use () after a name, it calls that function *immediately*.

Your second example would work as you expected if you simply remove the ():

$(function() {
    $('a.link1').click( clickFunction1 );
});

Now, instead of calling clickFunction1 immediately, your code merely takes a reference to that function and passes it into the click() method.

Make sense? Give a shout back with any questions...

-Mike

On Sat, Dec 12, 2009 at 3:01 AM, Jojje <jojjsus_christ@hotmail.com> wrote:
Ok, thank you for your anwer :) Appreciate it!
One more question.

If i use the code in example 2 the function gets triggered without me
clicking the link, in example 2 it gets triggered only when i click
the link.
Dont know if i´m doin anything wrong here? Shouldnt both examples work
the same?

1.
$(function() {
   $('a.link1').click(function() {
      clickFunction1();
    });
});

2.
$(function() {
    $('a.link1').click(clickFunction1());
});



function clickFunction1() {
  //code
 }

George

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate