Home > Software design >  How do I access an object created within an addEventListener?
How do I access an object created within an addEventListener?

Time:11-10

In the code shown below, I have a function that adds an object to an array. This object has a property named status which has a value of true. An addEventListener for a button named "check for true object" is able to access the 'true' object and log it in the console. I also have an addEventListener for a button which adds another object to the array. This added object also has a property named status which has a value of false. Then, there is an addEventListener for a button named "check for false object" which is to access the added 'false' object and log it in the console. However, when this "check for false object" button is clicked, it logs undefined even though the 'false' object has already been aded to the array. How can I solve this problem?

const button1 = document.querySelector('#btn-one');
const button2 = document.querySelector('#btn-two');
const button3 = document.querySelector('#btn-three');

const MainArrayModule = (() => {
  let mainArray = [];

  function MainArrayObjCreator(name, status) {
    return {name, status};
  }

  function createMainArrayObj() {
    let mainObj = MainArrayObjCreator('main', true);
    mainArray.push(mainObj);

    console.log(mainArray);

    button1.addEventListener('click', () => {
      let otherObj = MainArrayObjCreator('other', false);
      mainArray.push(otherObj);
      console.log(mainArray);
    });
  }

  return {mainArray, createMainArrayObj};
})();

const CheckArrayModule = (() => {
  MainArrayModule.createMainArrayObj();
  
  let trueObject = MainArrayModule.mainArray.find(object => object.status === true);
  let falseObject = MainArrayModule.mainArray.find(object => object.status === false);
  
  function logObject() {
    button2.addEventListener('click', () => {
      console.log(trueObject);
    });

    button3.addEventListener('click', () => {
      console.log(falseObject);
    });
  }

    return {logObject};
})();


const runFunctions = (() => {
    CheckArrayModule.logObject();
})();
body {
  display: flex;
  height: 100vh;
  justify-content: space-evenly;
  align-items: center;
}
<button id="btn-one">
  Add 'false' object
</button>
<button id="btn-two">
  Check for 'true' object
</button>
<button id="btn-three">
  Check for 'false' object
</button>

CodePudding user response:

When you run the CheckArrayModule function, it is ran once. In this you define false object. Because the false object does not exist at that time, the value of falseObject is undefined.

Short Answer: When you reference falseObject, it does not search for the false object because it already has when the object did not exist.

To fix this, move the two variable declarations inside your event listener so they are ran whenever the button is clicked.

The following example should work how you want it to.

const button1 = document.querySelector('#btn-one');
const button2 = document.querySelector('#btn-two');
const button3 = document.querySelector('#btn-three');

const MainArrayModule = (() => {
  let mainArray = [];

  function MainArrayObjCreator(name, status) {
    return {name, status};
  }

  function createMainArrayObj() {
    let mainObj = MainArrayObjCreator('main', true);
    mainArray.push(mainObj);

    console.log(mainArray);

    button1.addEventListener('click', () => {
      let otherObj = MainArrayObjCreator('other', false);
      mainArray.push(otherObj);
      console.log(mainArray);
    });
  }

  return {mainArray, createMainArrayObj};
})();

const CheckArrayModule = (() => {
  MainArrayModule.createMainArrayObj();
  
  function logObject() {
    button2.addEventListener('click', () => {
        let trueObject = MainArrayModule.mainArray.find(object => object.status === true);
      console.log(trueObject);
    });

    button3.addEventListener('click', () => {
        let falseObject = MainArrayModule.mainArray.find(object => object.status === false);
      console.log(falseObject);
    });
  }

    return {logObject};
})();


const runFunctions = (() => {
    CheckArrayModule.logObject();
})();
body {
  display: flex;
  height: 100vh;
  justify-content: space-evenly;
  align-items: center;
}
<button id="btn-one">
  Add 'false' object
</button>
<button id="btn-two">
  Check for 'true' object
</button>
<button id="btn-three">
  Check for 'false' object
</button>

CodePudding user response:

This was really hard to follow, so I broke it down a little more for you. You can adjust the alerts to do more whatever you're looking to do with this.

const button1 = document.getElementById('btn-one');
const button2 = document.getElementById('btn-two');
const button3 = document.getElementById('btn-three');

const ObjectStatus = [{
  name: 'main',
  status: true,
}, ];

const SetObject = (options) => {
  ObjectStatus.push({
    name: options.name,
    status: options.status
  });
};

const GetStatus = (status) => {
  return ObjectStatus.filter((obj) => obj.status === status);
};

const DisplayStatus = (status) => {
  const Status = GetStatus(status);
  const DisplayMsg = `${Status.length > 0} ${JSON.stringify(
    Status,
    null,
    '\t'
  )}`;
  alert(DisplayMsg);
};

// These do not need to be within the event listeners, just one for each button
// This one watches for adding false object
button1.addEventListener('click', () => {
  const CreateObject = window.prompt('What name for false status?', 'other');
  SetObject({
    name: CreateObject,
    status: false
  });
});
// This one adds objects
button2.addEventListener('click', () => {
  DisplayStatus(true);
});
button3.addEventListener('click', () => {
  DisplayStatus(false)
});
body {
  display: flex;
  height: 100vh;
  justify-content: space-evenly;
  align-items: center;
}
<button id="btn-one">
  Add 'false' object
</button>
<button id="btn-two">
  Check for 'true' object
</button>
<button id="btn-three">
  Check for 'false' object
</button>

  • Related