触发 jquery 没有匿名函数的事件函数

Trigger jquery event function without anonymous function

我还没有找到我想了解的问题的答案。 如果有人可以帮助我,我将不胜感激: 我正在做一个 JavaScript 项目,我需要传递一个事件函数作为回调函数的参数。 有办法得到这个吗?

我知道这很好用:

function callback(){
    alert("called!");
}
function trigger_callback(message, callback){
    alert(message);
    callback();
}
trigger_callback("I will call a function", callback);

但是我需要的是这样的:

trigger_callback("I will focus an input", $("#input").focus);

我收到错误:

TypeError: this._focus is undefined

到目前为止,我一直在使用:

trigger_callback("I will focus an input", function(){$("#input").focus();});

我需要一种更简单的方法。 另外,有人能解释一下为什么会失败吗?

var $tester = $('#tester');
var $tester2 = $('#tester2');

//focus is called while attached to the $tester, so it's context (this) is the $tester
$tester.focus();

//grabbing the method, you lose the context
//focusMethod does not have a context of the $tester
//it's context, in this case, would be the window as it's a global variable
var focusMethod = $tester.focus;

try {
  focusMethod();
} catch (e) {
  console.log('expected error');
}

//we can use bind, which will create another instance of the method, but
//will force the context on it to be $tester
var forceContext = $tester2.focus.bind($tester2);

forceContext();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tester">
<input type="text" id="tester2">