Search code examples
javascriptfunctionreturnglobal-variablesaddeventlistener

How is it possible to return something to a function called by an Event Listener?


Is it possible to return the result of a function if it is called by an event listener? I have tried lots of ways but nothing works. To my surprise there is not much information regarding it that can help me out. I would like to pass in the current score , increment it by one when an event occurs and return. Obviously what i have done below will not work because a) there is no storage for the return statement and b) it is called by an event listener. The only thing i am resorting to doing is changing my global variable inside the function. I know that wouldnt be as harmful if wrapped in an IIFE or its own closure but i still dont want to get in the habit of doing it. Is there anyway of incrementing the score by 1 and not referencing the global score variable inside the function directly, thanks all

const btn = document.querySelector('#btn');

let score = 0;

btn.addEventListener('click', function () {

    increaseScore(score); // passing in the current score varialble
})


function increaseScore(currentScore) { 

    currentScore++;
    return currentScore;      // there is nowhere to return this!!

}

Solution

  • The trick is you need to bind the context(this)

      someMethod.bind(this);
    

    const btn = document.querySelector('#btn');
    const scoreBtn = document.querySelector('#score');
    
    let score = 0;
    
    
    btn.addEventListener('click', function() {
      event.preventDefault();
      someMethod.bind(this);
      score = someMethod(score);
    });
    
    scoreBtn.addEventListener('click', function() {
      event.preventDefault();
      console.log(score);
    });
    
    function someMethod(cur) {
     return cur + 1; 
    }
    <button id="btn">Update Score</button>
    <button id="score">Show Score</button>