TransWikia.com

Call parent class method (with this context) in child class

Stack Overflow Asked by rjoxford on December 27, 2021

I’ve used JS frameworks in which interaction with a child component calls an action on a parent component. I’m trying to do something similar in plain JS, but don’t really know how. I’m trying to bind the parent this, to the action passed down to the child. But can’t make it work.

Should I just be using events instead? And why use events over this sort of approach?

Here’s the basics of what I’m trying to do:

class Parent {
    constructor(){
        for (let id=0; id<100; id++){
            this.children.push(new Child(id, this.updateParent.bind(this)))
        }
    }
    property = "Parent Property";
    children;
    updateParent(childId){
        // Update parent using child Id
        // I want to use this.property or other this.methods
    }
}

class Child {
    constructor(id, updateParent){

        // Create HTML element
        // Register event for element interaction
        // Upon interaction --
            updateParent(id)
    }
}

const parent = new Parent()

Thanks!

2 Answers

You have to define the children first.

Take a look at this:

class Parent {
    constructor(){
          this.children = [];
        for (let id=0; id<100; id++){
            this.children.push(new Child(id, this.updateParent.bind(this)))
        }
    }
    property = "Parent Property";
    children;
    updateParent(childId){
        // Update parent using child Id
        // I want to use this.property or other this.methods
        console.log("Parent updated from Child ID: "+childId);
    }
}

class Child {
    constructor(id, updateParent){

        // Create HTML element
        // Register event for element interaction
        // Upon interaction --
            updateParent(id)
    }
}

const parent = new Parent()

Answered by Sakibur Rahman on December 27, 2021

What you have seems to be almost working, here it is with some tweaks and logging.

Callback methods are a legit way of event handling, try both and use whichever is more comfortable for the kinds of interactions you need in your system.

class Parent {
  constructor() {
    this.children = []
    for (let id = 0; id < 10; id++) {
      this.children.push(new Child(id, this.updateParent.bind(this)))
    }
  }
  childCount = 0
  updateParent(childId) {
    console.log(`Child ${childId} updating Parent. youngest=${this.youngestChild}, count=${this.childCount}`)
    this.youngestChild = childId;
    this.childCount += 1;
  }
}

class Child {
  constructor(id, updateParent) {
    console.log("Child Born:", id)
    this.id = id
    updateParent(id)
  }
}

const parent = new Parent()
console.log(parent.children)

Answered by Luke Storry on December 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP