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
}
CodePudding user response:
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);
}