0

I am trying to create a controller in Javascript, which will respond to button clicks and change the view accordingly.

I have a function which works that looks like this:

document.getElementById("reset").onclick = function () { 
    //do something

   };

However, when I try to put the function in a controller object, I get an "unexpected token" error:

var controller = {
  this.reset = document.getElementById("reset").onclick = function () { 
    //do something

   };
}

I'm not sure about 2 things:

  1. How to fix this error? (I know its due to scope, but don't know how to fix it in a way that still follows MVC patterns)
  2. Generally speaking, is this a good way to go about creating a controller object? (I'm new to the MVC model, and don't know if I'm following best practices.)

Thanks.

2 Answers 2

2

The error is due to that the object cant be declared like that, there are different ways to do it:

var obj1 = { 
    a : function() { 
        console.log('obj1'); 
    } 
};

var obj2 = function() { 
    var b = function() { 
        console.log('obj2');
    };

    return { 
        a: b
    }
};

var obj3 = function() {
    this.a = function() { 
        console.log('obj3'); 
     } 
};

And then use it.

obj1.a; //prints obj1
obj2().a; //prints obj2
new obj3().a; //prints obj3. 

About how to structure your objects is opinion based, but i like to do it like this.

var Controller = function() {
    this.attachEvents = function() {
        document.getElementById("reset").onclick = reset;
    }

    var reset = function() {
        console.log('reset');
    };
}
new Controller().attachEvents();

another option is..

var Controller = function() {
    this.reset = function() {
        console.log('reset');
    };
}
var controller = new Controller();
document.getElementById("reset").onclick = controller.reset;
Sign up to request clarification or add additional context in comments.

Comments

2

This is not a valid Javascript object structure, but you can do it in following if it works for you

var controller = {
  reset : function () { 
    document.getElementById("reset").onclick = function(){
       //do your work here
     }
   }
}

Logic is completely on you/developer how he/she wants to handle things.

or you can do the binding thing outside, like,

var controller = {
      reset : function () { 
         //what to do to rsest
       }
    }

and then, bind it elsewhere

//when to run reset method
document.getElementById("reset").onclick = controller.reset;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.