简体   繁体   中英

Angular - How to call a function from inside an object

I'm wondering how can I call a function inside an object. I created here a quick demo .

Basically the idea is that I get some number from the user, I filter that number looking for the same value in my object and then I run a specific function.

btw, maybe there is some nicer way to code that, webstorm suggested me to create functions outside my component idkw

Thanks for any suggestions :)

You probably wanna have reference to the function rather than the function call in the Object. Something like setDate: currentDate rather than setDate: currentDate() . Your code works after this change.

Improvements:

Use in-place arrow functions in the object like so

datePeriods = [
  {
    name: "Currenty",
    value: 1,
    setDate: () => console.log(1)
  },
  {
    name: "Last",
    value: 2,
    setDate: () => console.log(2)
  },
  {
    name: "Custom",
    value: 3,
    setDate: () => console.log(3)
  }
];

Not exactly why they'd prefer using functions defined outside the scope. Unless you wish to reuse the function elsewhere, you could define the functions as inline arrow functions.

datePeriods = [
  {
    name: "Currenty",
    value: 1,
    setDate: () => { console.log('current date') }
  },
  {
    name: "Last",
    value: 2,
    setDate: () => { console.log('last date') }
  },
  {
    name: "Custom",
    value: 3,
    setDate: () => { console.log('custom date') }
  }
];

And Array#filter is used to generate an array based on a certain condition. Since you wish to only run the function when the condition is met and exit, you could use Array#some instead.

onSelectedDate() {
  this.datePeriods.some(data => {
    if (this.selectedDate === data.value) {
      data.setDate();
      return true; // <-- skip the following iterations
    }
  });
}

I've updated your Stackblitz .


Note: While you could also use Array#forEach here, it'd continue to run even after the condition is met. Thus would lead to unnecessary iterations. Array#some on the other hand would short-circuit as soon the condition is met.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM