Binding an existing JavaScript function in jQuery

爱⌒轻易说出口 提交于 2019-11-30 00:11:36

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);
}

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.

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!