Controllers are just regular event handlers! The only difference is that jquery-claypool decorates the event object with some handy, dandy, mvc to help you cleanly separate your event handling from your presentation and data access functions. We will cover these functions here because they will generally only ever be used in your controllers, but first lets go over a couple things that will help you avoid common mistakes if you are new to mvc.
It's true, they never go out and have fun, being a total control freak is their nature. This means they don't have ajax calls directly inside them (that's the models job), they just pickup the phone and order a pizza, and are ready to eat when it shows up.
They are news junkies. But they don't make the news. This just means that controllers are free to peruse all the info they want in the DOM but they should leave the presentation to the views. It's not a steadfast rule, sometimes a controller will modify the DOM, but usually only in ways you don't see.
The title say's it well, but you should check out the specifics here.
Let's start by creating a simple closure that will define our controller.
/*
* @file app/controllers/hello.js
* @description You can feel free to use your
* own writing style, we are providing an
* example not a rigid requirement of how to
* you have to write event handers. If you
* want to take advantage of the mvc scanners
* (and keep the global scope clean) you should
* use a closure and single top-level namespace.
* In this example we use 'MyApp'
*/
(function($, $C){
$C.Hello = function(options){
$.extend(true, this, options);
};
$.extend($C.Hello.prototype, {
handle: function(event){
//event handling code here
}
});
})(jQuery, MyApp.Controllers);
This is a good lazy controller because it doesn't actively do anything when the anonymous closure is executed other than define itself.
Lets start using this mvc thing a little but keep it real simple.
handle: function(event){
event.m({
first_name:'chris',
last_name:'thatcher',
order:[{
type:'pizza,
opts:['cheese', 'anchovies', 'pineapple', 'black beans'],
quantity: 5
}]
}).render();
}
WoW! That was amazing! But very presumptuous, because I would have wanted some hamburger on it today as well...
Lets dive in.
handle: function(event){
event.
v('.think'). //show activity in progress
render(function(){ //mvc callback after '.think'
$.$('#pizzaModel').order( //order the pizza via ajax
event.params(), //(mmm hamburger)
function(model){ //ajax callback from model
event.
m(model). //json summary of order
v('.update'). //update the page
render();
});
});
}
OMG! How jquery-ish! indeed. To learn more just dive in!