Joe Consterdine Joe Consterdine - 9 months ago 60
Javascript Question

Undefined Javascript Error On Click

not sure why I'm getting this error when I attempt to click on the button.


Uncaught TypeError: Cannot read property 'on' of undefined


JSFiddle: https://jsfiddle.net/mm5crd3b/

Thanks

$(document).ready(function(){

(function() {
var itemTracker = {
// init
init: function() {
this.bindEvents();
},

// cacheDom
cacheDom: {
inputAdd: $('#inputAdd'),
submitAdd: $('#submitItem')
},

// item
item: {
text: this.inputAdd.value,
},

// Bind Events
bindEvents: function() {
this.submitAdd.on("click", addItem);
},

// Add item
addItem: function() {
console.log("test");
}

// Remove item

// Edit Item

// Complete Item

// Uncomplete Item
};

itemTracker.init();

})();

});

Answer Source

You are accessing the property in a wrong way,

bindEvents: function() {
  this.cacheDom.submitAdd.on("click", addItem);
},

When seeing your code, I can tell cacheDom is an object which holds submitAdd as a property in it.

Additionally,

item: {
 text: this.inputAdd.value,
},

This part of the code wont work as expected. You can write it as a getter to solve your problem.

get itemText() {
 return this.cacheDom.inputAdd.value,
},