Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding an existing JavaScript function in jQuery

Tags:

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 site bind newly created functions where as I want to bind a function that's already defined, e.g:

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

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

like image 549
Jack Mills Avatar asked Sep 05 '09 19:09

Jack Mills


People also ask

How do you bind a function to click an event in jQuery?

jQuery bind() MethodUse the on() method instead. The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.

What is the purpose of using bind () method in jQuery?

The bind() is an inbuilt method in jQuery which is used to attach one or more event handlers for selected element and this method specifies a function to run when event occurs. event: This is an event type which is passed to the selected elements.

How do you bind a function?

JavaScript Function bind()With the bind() method, an object can borrow a method from another object. The example below creates 2 objects (person and member).

How can two way binding in jQuery?

Create bindings. $('#form'). bindings('json')('#model-selector'); // or $('#form'). bindings('json')('#model-selector', '<input type="text" data-model="firstname" /><span>your firstname: <b data-model="first-name"></b></span>'); // or $('#form').


2 Answers

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); } 
like image 53
Gumbo Avatar answered Oct 12 '22 13:10

Gumbo


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.

like image 44
David Andres Avatar answered Oct 12 '22 14:10

David Andres