This is really getting me frustrated. I’m trying to build a custom JavaScript app with no libraries. This is mainly for me to learn better core JavaScript and JavaScript patterns. I’m trying to implement the MVC structure and I understand the parts separately, but for the life of me I can’t figure out how to connect the views and controllers together. For example if I have this code:
<div>
<button id="button1">Click Me</button>
<button id="button2">Click Me</button>
<button id="button3">Click Me</button>
</div>
How in the world do I write a controller.js file to listen to the clicks of each button and respond. Especially if each button does something totally different from the others. Let’s say button1 simply links to google.com, button2 opens a modal box and button3 updates a database table. So each one is doing something totally separate. What I am trying to avoid is using jQuery to do something like this.
$('#button1').click(function(){
//go to google.com
});
$('#button2').click(function(){
//open modal box
});
$('#button3').click(function(){
//update database
});
This doesn’t seem very efficient, especially when trying to use the MVC structure. Is there a smoother way, even a few different design patterns I can follow to write this is core JavaScript with no libraries? I scoured the net to find articles but everything I find relies heavily on a library.
Any books, tutorials, blog posts or anything of the like that will clearly explain something like this is much much appreciated. Who knows once I get the hang of it maybe I’ll write a book on it for the masses.
Once again the help of the community is always appreciated.
You are writing an application in Javascript, following the MVC design pattern, and it’s a great idea to understand core javascript, as you will have to adapt existing design patterns on js 🙂
I would have parsed the DOM recursively at first, retrieving each tag, and then associated them simple click event code that call a click_event generic (and global) function, with the button id as parameter, to have a single entry point that identify the button.
Then this generic method (event entry point) would have to select and launch the appropriate controller for the action.
You might also go one step further with 2 parameters: objectId or reference, and event type. This is very similar of what you will find on many basic GUI to fire events.