0

I am trying to bind values to a function in a loop. How can I access the binded values in the function?

// ansswer number is is different each time
 btn.find("a").data(this.key, option.slide).bind("click", this._continueOnClick.bind(answerNumber));

Now from the function _continueOnClick, how can I actually access the value of answerNumber?

The function:

_continueOnClick: function (e) {
    console.log(answerNumber); //fails
}
11
  • 1
    console.log(e)?? Commented Aug 26, 2022 at 14:26
  • What is the use of the JavaScript 'bind' method? explains in details how bind can be used. The first argument passed to bind will be found in this. Commented Aug 26, 2022 at 14:28
  • Unfortunately not. That prints <span>option text</span> Commented Aug 26, 2022 at 14:29
  • can you share something that we can reproduce? Commented Aug 26, 2022 at 14:30
  • 2
    console.log(this) has to work. If not then the code you show and the one you actually have do not match. Commented Aug 26, 2022 at 14:42

1 Answer 1

1

Bind's first parameter is what you want to pass as this, but it will expect an object here, if you send a primitive it will convert into the Object version, eg. number to Number(), so you could just use this.valueOf().

But another option, you can pass more params, you can just pass null or some other object as the first parameter. These extra params will then be available in the callback's parameters and can also be primitives, not just objects..

Here is an example..

for (let answerNum = 0; answerNum < 10; answerNum++) {
  const btn = document.createElement('button');
  btn.innerText = answerNum;
  document.body.appendChild(btn);
  btn.addEventListener('click', click.bind(null, answerNum));
}

function click(answerNum) {
  console.log(answerNum);
}

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

Comments

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.