views:

308

answers:

5

You can do this with JavaScript:

function bar(test) {
    alert(test);
}
var foo = bar;
foo('hi');

I'd like to be able to do something similar with a jQuery event:

var foo = $('#bork').click;
foo(function() { alert('I was just clicked.'); });

However, I get an error when the page loads: this.bind is not a function. Am I doing something wrong with the events here? Is there a better way to get the same effect?

A: 

I think you are looking for the bind function.

$('#bork').bind("click", function() { 
    alert('I was just clicked.'); 
});
Andrew Hare
A: 

Try the following:

$("#bork").bind("click", function() { alert("I was just clicked"); });
jonstjohn
A: 
$('#bork').bind('click', foo);
function foo() { alert('i was just clicked'); }
Paolo Bergantino
I knew it had something to do with bind(). Thanks.
swilliams
There is no difference in functionality at all between $("#bork").click(...) and $("#bork").bind("click", ...). Refer to Kip's reply to see the real issue here.
Alex Barrett
You and Kip both misunderstood his question. Kip's remarks are no doubt interesting but they're not addressing what he is trying to do, which my answer does.
Paolo Bergantino
A: 

You need to define foo as a function to make your sample work. If you change the definition of foo a little it will work:

var foo = function(f) {$('#bork').click(f);};
foo(function() { alert('I was just clicked.'); });
Thomas Petersen
+2  A: 

The other answers don't seem to be addressing the technical question:

Why does this work:

$('#bork').click(function() { alert('I was just clicked.'); });

But not this:

var foo = $('#bork').click;
foo(function() { alert('I was just clicked.'); });

The two appear to be the same, but the problem is that "this" within the implementation of the click function refers to the jQuery object in the first example, but it refers to foo in the second example. Since you have not defined foo.bind, the call to "this.bind" in the implementation of click fails.

Here is a great article about the ins and outs of binding/scoping in Javascript.

Kip
Thanks for the explanation!
swilliams