Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Listen to callback from child method from parent class

I’d like to ask you about the correct approach to dealing with children’s classes that have their inner logic.

I have a class called MainClass. The purpose is to grab all smaller classes(called A class) and grab them into an array. On destroying it should do some stuff within itself(in the example code it triggers the console log) and later inform the MainClass to be removed from the array of active objects. There’s no connection to the DOM.

I have a few questions:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. How should I do this in plain Javascript? The only idea I have is to override one of the functions that is triggered inside the code, but I’m not sure if this is the correct approach.
  2. If this is the correct approach how should I pass the data to the MainClass? Currently, after pushing it to the array, I’m losing context.
  3. If I replace const with let in temporaryVar, override function outputCallback() in MainClass, push temporaryVar to the array, and then override it with another class will it be detectable by GarbageCollector on deleting the original class from the array?
class A {
  name = 'class a';

  destroyCallback() {
    // do its stuff
    console.log(this.name);
    this.outputCallback()
  }
  
  outputCallback() {
    // this should inform MainClass that it was finished + return some data
  }
}

class MainClass {
 classArr = [];
  constructor() {
    const temporaryVariable = new A();
    
    // wrong attept - overrides inner function
    temporaryVariable.outputCallback = () => {
      // do some stuff
    }
 
    classArr.push(temporaryVariable );
  }
}

>Solution :

A common pattern is to take in a callback function in the constructor, which you call to notify the code above you that you’ve completed your task.

In this case, you could write something like

class A {
  constructor(onDestroyed) {
    this.onDestroyed = onDestroyed
  }

  // ...

  outputCallback() {
    this.onDestroyed?.(this);
  }

}

class MainClass {
  classArr = [];

  constructor() {
    const removeInstanceFromClassArr = (instance) => {
      this.classArr = this.classArr.filter((item) => item !== instance);
    };

    this.classArr = [
      new A(removeInstanceFromClassArr)
    ];
  }
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading