I know that probably there might be a better way to do this, but I want to understand how to solve this kind of problem. I have two classes, Parentand Child. Parent holds an array of children.
I created a addChild and removeChild methods that allow me to create a Child and remove it and both return me the updated Parent object ( I need it because it is going to update a React state variable somewhere else)
I want to pass to each child a method "remove" in order to remove it from its parent.
This actually works fine on a preset parent with children. But if I add many children and then try to remove one, everytime I go back to the initial condition, (say, Parent initially has 4 children, I add 3 more, now they're 7. I remove one and go back to 4.).
I think this happens because when I pass the handler to the Child object I'm creating in addChild, the removeChildfunction I embed in the child is not updated and refers to the initial version of the Parent object, but I don't know how to fix this.
I attach here some pseudocode, just to give an idea of the problem.
Any help would be appreciated.
import _ from "lodash";
class Parent{
constructor(){
this.removeChild.bind(this);
}
children: Child[];
addChild(){
const newParent = _.cloneDeep(this);
newParent.children = [
...newParent.children,
new Child({remove: this.removeChild})
]
return newParent;
}
removeChild(child){
const newParent = _.cloneDeep(this);
newParent.children = newParent.filter(child => (child.id != child.id));
return newParent;
}
}
class Child{
id;
remove();
constructor({remove}){
this.id = automaticgenerated
this.remove = remove
}
}
Do you mean something like this?
class Parent {
constructor() {
this.children = [];
}
addChild(child) {
child.parent = this;
this.children.push(child);
return this;
}
removeChild(child) {
child.parent = null;
this.children = this.children.filter(c => c.id != child.id);
return this;
}
}
class Child {
constructor() {
this.parent = null;
this.id = Math.random(); //Fake auto generated id
}
remove() {
this.parent.removeChild(this);
this.parent = null;
}
}
const p = new Parent();
const c1 = new Child();
const c2 = new Child();
console.log(p.addChild(c1));
console.log(p.addChild(c2));
console.log(p.removeChild(c2));
c1.remove();
console.log(p);