So I'm doing a tutorial on one of the videos I found online. In that tutorial, he used IIFE to create mvc model rather than object literals.
I decided to recreate the project using object literals
This is the problem that I am having right now and I'm not sure what the problem is. I suspect it has something to do with scoping problem.
This is the code for the controller and at the end I initiate the init().
var model ={ //Code }
var view = {//Code}
var controller = {
dom: view.getDom(),
setEventHandler: function(){
document.addEventListener("keypress", function(ev){
if(ev.keyCode === 13){
this.addItem();
}
});
},
addItem: function(){
this.updateMethod();
// Code
},
init: function(){
this.setupEventHandler();
},
updateMethod: function(){
// Some code
}
{
controller.init();
Now when I press the enter key to invoke the event, i get an error from the console. It states:
"Uncaught TypeError: this.addItem is not a function at HTMLDocument.[anonymous]"
Question: Why is it not recognizing the addItem()?
The same error message occurs within addItem() when I try to invoke this.updateMethod() too.
One way I found to have this.addItem() to get invoked in the event listener is by using () => rather than using a regular anonymous function declaration.
document.addEventListener("keypress", (ev) => {
if(ev.keyCode === 13){
this.addItem();
{
});