Search code examples
javascriptobjectconstructorprototypeparent-child

How to access an object from a parent object constructor


Can I access the list object of the parent-object (TodoList) inside the prototype of a child-object (Todo)

Presume the next setup:

index.js :

var todoList = new TodoList(form,holder);

todolist.js :

function TodoList(form,holder){
  this.list = {};
  this.inputField = document.querySelector('input');
  this.submitButton = document.querySelector('button');
  this.todoHolder = holder;
  this.init();
}

TodoList.prototype.init = function(){
  this.submitButton.addEventListener('click',this.submitHandler.bind(this));
}

TodoList.prototype.submitHandler = function(e){
  var todo = new Todo(this.inputField.value, this.todoHolder);
}

todo.js :

function Todo(value, holder){
  this.id = nr++;
  this.value = value;
  this.checked = false;
  this.holder = holder;
  this.todoElement = "";
  this.template = `
    <li id="todo-{{id}}">
      <span>{{value}}</span>
      <a href="#" class="delete"></a>
      <a href="#" class="check"></a>
    </li>`;
  this.add(this.value);
}

Todo.prototype.add = function(value){
  //addToDom
  var html = this.template;
  this.holder.insertAdjacentHTML('beforeend', html.replace('{{value}}',value).replace('{{id}}',this.id));
  this.setUpEventListeners();
  ////// QUESTION
  // HOW CAN I ACCESS THE TODOLIST.LIST object here
  // I KNOW I COULD DO todoList.list (but that is by the instance that was created. Is it possible by accessing parent or something like that....      
}

Solution

  • The parent object that creates the TODO should add a reference, like so:

    TodoList.prototype.submitHandler = function(e){
      var todo = new Todo(this.inputField.value, this.todoHolder);
      todo.parent = this
    }
    

    Now this won't work in your current setup as your add method is being calling in the constructor which is before the todo.parent has been set.

    So to get around this you should pass it in on the init of the Todo instead

    TodoList.prototype.submitHandler = function(e){
      var todo = new Todo(this, this.inputField.value, this.todoHolder);
    }
    

    Which means this would be:

    function Todo(parent, value, holder){
      this.parent = parent 
      // rest of logic...
    }
    
    Todo.prototype.add = function(value){
      console.log(this.parent)
    }