3. The Javascript layer of a typical MVC app starts simple.
...like a jQuery Zen garden.
$(function(){
/* animate the blog title */
$('.title').slideDown();
});
4. As the project matures, things get a little more tricky.
$(function(){
/* animate the blog title */
$('.title').slideDown(350, function(){
$.get('/stats/count').done(function(data){
$('.statsCount')
.html(data.count)
.addClass('green');
});
});
});
Still maintainable... -ish
12. AMD EXAMPLE
Define your modules:
/* define(id?, dependencies?, factory); */
define("SomeModule", ["dependency"], function(dependency) {
var SomeModule = function(){};
SomeModule.prototype.init = function(){
dependency.doStuff();
};
/* etc. */
return SomeModule;
});
13. AMD EXAMPLE
Load your modules and use them:
/* require(dependencies, callback); */
require(["ModuleA", "ModuleB"], function(ModuleA, ModuleB) {
var module = new ModuleA();
ModuleA.init();
/* etc. */
});
18. TIPS
Keep your modules focused; remember the single
responsibility principle.
Define a solid directory structure, and stick to it.
(like your CakePHP /app directory)
Think "automagic" and document your conventions.
/js/README.md
20. DISCLAIMER
This works for us, and we like it, but feel free to tweak it to
meet your needs.
image from gifsoup.com
21. IDENTIFY SECTIONS FOR
YOUR PROJECT
1. Break the project down into sections, and create a
module for each section (e.g. blog.js, shop.js, etc).
2. Identify any functionality that would be shared across
multiple sections, and put them into common modules.
22. CHANGE THE LAYOUT
BEFORE:
/* (data-main does the heavy lifting) */
echo $this->Html->script("require.js", [
"data-main" => "/js/bootstrap"
]);
AFTER:
/* no more data-main */
echo $this->Html->script("require.js");
<script>
require(['/js/bootstrap.js'], function(){
require(['modules/<?php echo $javascriptModule; ?>']);
});
</script>
26. R.JS
RequireJS ships with a great minification/concatenation
tool
It runs in Node.js, Java with Rhino, or a browser
It is configurable
Bonus: it can minify CSS files for you too (but I'm not
going to cover that today)