views:

326

answers:

3

Using JQuery I want to bind an existing function to a button. I've been through the documentation and have found the bind method but the examples on the JQuery bind newly created functions where as I want to bind a function thats already hard coded, e.g:

function fHardCodedFunction(){
   //Do stuff
}

function fBindFunctionToElement(){
   $("#MyButton").bind("click", fHardCodedFunction());
}

Is this possible? Or am I going about this the wrong way?

+7  A: 

The plain fHardCodedFunction already refers to the function and the suffix () will just call it. So just pass the function instead of calling it and thereby just passing the return value:

function fBindFunctionToElement(){
   $("#MyButton").bind("click", fHardCodedFunction);
}
Gumbo
What if I need to pass the hardcoded function a parameter?
Jack Mills
@Jack Mills: Then you will need to use an (anonymous) wrapping function like `function() { return fHardCodedFunction("foo","bar"); }` that you pass as callback function to `bind`.
Gumbo
+1  A: 

Yes you can bind methods that written somewhere else, but you should ignore the parentheses :

function fHardCodedFunction(){
   //Do stuff
}

function fBindFunctionToElement(){
   $("#MyButton").bind("click", fHardCodedFunction);
}
Canavar
What if I need to pass the hardcoded function a parameter?
Jack Mills
+1  A: 

Borrowing from the other posts, you can parameterize your event handler as follows:

function fHardCodedFunction(someValue) {
  alert(this.id + " - " + someValue);
}


function fBindFunctionToElement() {
  var someValue = "whatever";
  $("#MyButton").bind("click", 
       function() {
         fHardCodedFunction.apply(this, [someValue]);
       }
  );
}


$(document).ready
(
  function() {
    fBindFunctionToElement();
  }
);

I'm using apply here because in function fHardCodedFunction I'd like the this property to refer to the MyButton element. Note also that apply expects an array for the second parameter, which is why I've wrapped someValue in brackets.

You don't have to do it this way and can forget about this this property altogether if you prefer.

David Andres