简体   繁体   English

在子 class 中调用父 class 方法(使用此上下文)

[英]Call parent class method (with this context) in child class

I've used JS frameworks in which interaction with a child component calls an action on a parent component.我使用了 JS 框架,其中与子组件的交互调用父组件上的操作。 I'm trying to do something similar in plain JS, but don't really know how.我正在尝试在普通 JS 中做类似的事情,但真的不知道怎么做。 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!谢谢!

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)

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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