0

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?

1 Answer 1

1

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">

Sign up to request clarification or add additional context in comments.

1 Comment

You are right! I was so close trying to use .bind(this) and .bind($) but I forgot that I must use the element as itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.