Page 4

The Controller

I pointed out earlier that the Model’s only job is to store data, and the View’s only job is to display data. We also had each of these notify listeners when something happened. The Controller is that listener. It’s the Controller’s job to listen to all of the events going on in the Model and the View (and potentially other models and views), and determine the correct behavior for the application.

In our simple demo, when the Controller hears from the Model that data has been loaded, it passes on a simple text message to the View. Similarly, when the Controller hears from the View that a button has been clicked, it requests the appropriate data from the Model.

Listen to the View

Let’s add a listener to the View and tie in our very simple application logic: when the user clicks a button, request data from the Model and send in some simple text messages back to the View.

 * listen to the view
var vlist = $.ViewListener({
    loadAllClicked : function(){
        var all = model.getAll();
        if(all) view.message("from cache: " + all.length + " items");
        $.each(all, function(i){
            view.message("from cache: " + all[i].name);
    loadOneClicked : function(){
        var d = model.getItem(1);
        if(d) view.message("from cache: " +;
    clearAllClicked : function(){
        view.message("clearing data");

Listen to the Model

On the other side of the application, we also need to listen to the Model. The Controller will send messages to the View whenever new data is loaded from the server.

 * listen to the model
var mlist = $.ModelListener({
    loadBegin : function() {
        view.message("Fetching Data...");
    loadFail : function() {
        view.message("ajax error");
    loadFinish : function() {
    loadItem : function(item){
        view.message("from ajax: " +;

That’s it!


These listener functions make it incredibly simple keep the view 100% in sync with the state of the Model. As the Model AJAX’s in data from the server, we can listen in and toggle Loading animations on or off, or disable portions of our forms, or just populate our UI with new data as it becomes available.

4 thoughts on “Page 4

  1. If I load a page via ajax (say in a fancybox popup) and in that page I want to use the loadItem function, how do I do it? I can’t access this function and I don’t know how to listen for it if the page was not created by the MVC.

Leave a Reply

Your email address will not be published. Required fields are marked *