Reputation: 1087
I haven't found an answer to the problem I am trying to understand. I would be thankful if someone can help me: I am working on a JavaScript project and I need to pass an event function as a parameter for a callback function. Is there a way to get this?
I know that this works fine:
function callback(){
alert("called!");
}
function trigger_callback(message, callback){
alert(message);
callback();
}
trigger_callback("I will call a function", callback);
But what I need is something like this:
trigger_callback("I will focus an input", $("#input").focus);
I get the error:
TypeError: this._focus is undefined
So far, I've been using:
trigger_callback("I will focus an input", function(){$("#input").focus();});
I need a simpler way to do it. Also, can someone please explain why this fails?
Upvotes: 0
Views: 40
Reputation: 24965
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">
Upvotes: 1