JavaScript- Remove object from parent array with an object's method

1.7k views Asked by At

I have a parent object that stores an array of children and calls some of their methods.

var Parent = function ()
{
     this.children = []
     this.addChildren();
}

Parent.prototype.addChildren = function ()
{
     for (var i=0; i < 5; i++)
     {
         this.children.push(new Child());
     }

     this.alterChildren();
}

Parent.prototype.alterChildren = function ()
{
     this.children.forEach(function (child)
     {
         if (child.hasSomeProperty.foo)
         {
              child.alter();
         }
     });
}

Then there are the child objects. When a certain event happens with them, I need them to be effectively destroyed and I null properties that the parent relies on.

var Child = function ()
{
   this.hasSomeProperty = {
      foo: 'bar'
   };
}

Child.prototype.onDestroyEvent = function ()
{
   this.hasSomeProperty = null;
}

I then want to remove this child from the parent's child array and have the child garbage collected. Is there an elegant way to do this without circular references or breaking my existing structures?

1

There are 1 answers

2
Tomalak On BEST ANSWER

If you want the child to send a message to the parent then the child needs to have a reference to the parent.

Parent.prototype.addChildren = function ()
{
    for (var i=0; i < 5; i++)
    {
        this.children.push(new Child(this));
    }
    this.alterChildren();
}
Parent.prototype.removeChild = function (child)
{
    var i = this.children.indexOf(child);
    return this.children.splice(i, 1);
}

and

var Child = function (parent)
{
   this.parent = parent;
   this.hasSomeProperty = {
      foo: 'bar'
   };
}

Child.prototype.destroy = function ()
{
   this.hasSomeProperty = null;    
   this.parent.removeChild(this);
}