Asynchronous Module Definition (AMD)
As with any MVC architecture, the folder structure is important and will be the foundation of our MVC pattern. This is how I decided to organize the structure:
Yes, that’s Sublime Text 2 🙂
This is RequireJS saying that my initial code is in ~/scripts/main.js. The module main.js defines some shortcuts to libraries and also initializes the router.
CanJS is used to create the router as so:
What a beautiful sight. Routes are cleanly mapped to controller and actions. The controller is just as nice:
Notice that DOM events are declared here in the controller. No more polluting your code with jQuery binding. Also the model is brought in as a dependency. The REST services are called in the underlying model, then the result is passed into the view.
The view is a template that allows binding of data. This is how the view looks like:
As you can see, the bindings are happening between the <% CODE %> magic tags. I am also using MomentJS to format the date. This dependency is declared in the controller which is why I can use it in the template. Otherwise, the view would not know what “moment” is. Another things worth mentioning in the view is that I am storing the model data in the “li” element with this line:
Latest posts by Guest Posts (see all)
- Head scratcher of the day, Ad Hoc SQL and reentrancy? - March 9, 2016
- IoT Greenhouse – Searching history and supporting documentation with Azure Search - February 7, 2016
- IoT Greenhouse – Machine Learning develops a disease model, part 3 - February 6, 2016
- IoT Greenhouse – Machine Learning develops a disease model, part 2 - February 6, 2016
- IoT Greenhouse – Machine Learning develops a disease model - February 6, 2016