Home > OS >  how to get/use object value out of event listener scope
how to get/use object value out of event listener scope

Time:01-16

I have 2 buttons with id and data-price. with every click on button the value will be added on array object with addEventListener. ok its fine, i can read the value in that scope but outside of that scope, i cant get it. Why? any other ways? array itself is outside the scope. If I adding it some value, i should be get it outside the scope too, I think.

<button  data-id="1" data-price="29">press1</button>
<button  data-id="2" data-price="60">press2</button>

const arr =  [];
const btn = document.querySelectorAll('button');

for(let button of btn){
  button.addEventListener('click', (el) => {
    const id = el.target.dataset.id;
    const price = el.target.dataset.price;

    arr.splice(0,0, {'id':id, 'price':price });
    
    //console.log( arr[0]['id'] ); // result is 1 the id number of first button
    //console.log( arr[1]['id'] ); // result is 2 the id number of second button
    
  });

}



 console.log( arr[0]['id'] ); // Cannot read properties of undefined (reading 'id') 

CodePudding user response:

I think you need to have a function call since you are wanted to log something is already in the stack and executed therefore you to make a function and call it simple but you still need to look into arr.splice logic but since that was not the original ask;

        const arr =  [];
        const btn = document.querySelectorAll('button');
        
        for(let button of btn){
          button.addEventListener('click', (el) => {
            const id = el.target.dataset.id;
            const price = el.target.dataset.price;
        
            arr.splice(0,0, {'id':id, 'price':price });
            
             callback(); // calling here
            //console.log( arr[0]['id'] ); // result is 1 the id number of first button
            //console.log( arr[1]['id'] ); // result is 2 the id number of second button
            
          });
        
        }
        
        
        function callback(){
         console.log( arr[0]['id'] ); // Cannot read properties of undefined (reading 'id') 
        } 
 console.log( arr[0]['id'] ); // Cannot read properties of undefined (reading 'id') 
  • Related