I'm practicing MVC in javascript and I'm trying to attach an event handler in a controller to a button. First I create the view and in the contructor of it, I load external HTML. Then, in the controller constructor, I try to do find("#myButton")
in order to find my button and then attach an event listener to it. Here's my attempt:
index.html:
<div id="welcome"></div>
js/app.js:
var welcome = $("#welcome");
var welcomeView = new WelcomeView(welcome, model);
var welcomeController = new WelcomeController(welcome, model, generalController);
js/view/welcomeView.js:
var WelcomeView = function(container, model){
var container = container;
var model = model;
container.load("welcome.html");
this.show = function(){
container.style.display = "block";
}
this.hide = function(){
container.style.display = "none";
}
}
welcome.html:
<button type="button" class="btn btn-default" id="myButton">Create new dinner</button>
js/controllers/welcomeController.js:
var WelcomeController = function(container, model, generalController){
var container = container;
var model = model;
var createButton = container.find("#myButton");
createButton.click( function() {
alert("entered");
generalController.showScreen("DISHSEARCH");
} );
}
When I click the button, nothing happens. And when I try without jQuery in the controller:
createButton[0].onclick = function(){
alert("hello");
};
I get the error:
welcomeController.js:7 Uncaught TypeError: Cannot set property 'onclick' of undefined
at new WelcomeController (welcomeController.js:7)
at HTMLDocument.<anonymous> (app.js:30)
at fire (jquery.js:3119)
at Object.fireWith [as resolveWith] (jquery.js:3231)
at Function.ready (jquery.js:3443)
at HTMLDocument.completed (jquery.js:3474)
So there seems to be some problem with finding the button element, but I can't figure it out! What is wrong here?