Let's start with the part I'm sure you love: creating all the folders and files of our project. Considering our simple app case, we'll have 2 controllers, 2 views and 1 model.
We want to use Models to represent data, the business logic will be handled by Controllers, and those controllers will call specific Views to render pages. Our Java Script folder now looks like this: in the require method, and manually create a set of users for the purpose of this example: We then serialize in JSON the users array and store it in the HTML5 local storage to make it accessible just like a database: Note: JSON serialization with element.
In this step by step tutorial you will learn how to build a simple MVC (Model - View - Controller) app using Require JS.
You don't need any particular previous knowledge of script loading - we'll see the basics together.
Now, all we need to do is to "run" our : You can now refresh your page to get this wonderful list of users: Woooaaaah, it works! Note: For the moment, we can only manually declare the controller we want to run since we don't have any routing system yet.
But we'll create a very simple one pretty soon, be patient! We'll display a simple text input and a button, with an event handler when the button is clicked to add the user to the local storage. If we put it in the view it would be the right place to add the events listeners, but putting the business logic in a view would be a very bad practice.
It's time for you to take a break, you've done a very good job if you're still doing this example with me. Java Script single page interfaces like this one use the hash of the URL to navigate between different parts of the app.
In our case, we want to be able to reach the 2 different views when hitting those URLs: This will make each page of our app bookmarkable and easily reachable.
Let's start with method to successfully get the expected view: But since we don't have any event bind on the button yet, this view is not very useful... I have a question for you: Where should we put the event logic for this event? Putting the event logic in the controller seems to be a better idea, even if it's not perfect because we don't want to see any div's ID in there, which belong to the view.
Note: The best way to go would be having event listeners in the view, which would call business logic methods located in the controller or in a new dedicated events module.
If this happened to you, you certainly understand that there is a strong need to organize our front-end code differently, particularly if we have to build large-scale web apps with thousands of lines of Java Script.
We need a new way to organize all this mess to make it easier to maintain.
Because the web changes quite fast, some information here might be outdated.