Adding eventlistener to object in Javascript

mikeLspohn

I did a project for a to-do list and am trying to refactor it to be more object oriented. I'm having trouble figuring out how to make an object that adds an item to my list. After looking at many different examples, and answers to similar questions this is what I have now, but it doesn't work.

function Todo(){
  this.btn = document.getElementById('add');
  this.item = document.getElementById('item').value;
  this.list = document.getElementById('list');
  this.el = document.createElement('li');
  this.el.innerHTML = this.item;
  this.handler = function(){
    this.list = appendChild(el);
  };
  this.action = function(){
    this.btn.addEventListener('click', function(e){this.handler.bind(this);});
  };
}


var mine= new Todo();
mine.action();

I'm honestly not sure what I'm stuck on, but I'm fairly sure my eventListener itself in the this.action function is wrong.

HTML is as follows.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Todo</title>
</head>
<body>
  <h1>ToDo List</h1>
  <p>This is a todo list</p>
  <ul id='list'>

  </ul>
  <input id='item'></input>
  <button id='add'>Add Item</button>

</body>
</html>
Rafael Eyng

This is a better way to write your code:

var TodoList = function() {
  this.addTodoItem = function() {
    var todoText = document.getElementById('item').value;
    var todoUl = document.getElementById('list');
    var todoLi = document.createElement('li');
    todoLi.innerHTML = todoText;
    todoUl.appendChild(todoLi);
  };
};

var todoList = new TodoList();

var bindEvents = function() {
  document.getElementById('add').addEventListener('click', todoList.addTodoItem);
};

var init = function() {
  bindEvents();
  // do any other initialization you want
};

window.onload = init;

First off, your Todo constructor. You were storing a bunch of DOM element objects as properties of some instance of the newly created Todo object (your mine variable). There is no need for that. You just want to use these elements temporarialy. So, use local variables, as I did inside of addTodoItem.

Then we create an instance of the TodoList, which will handle any interaction with your todo list.

Also, it shouldn't be your constructor responsability to make the event bindings. Because of that, I've created the init function, which will be called after the full page load. That is a pretty standard place for attatching events (considering you are not using jQuery). So, I got rid of your action function inside of the TodoList, and attached a function of the todoList object (which will be the object that will handle your todo list stuff) to handle the desired events.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related