simple.js client side MVC* kept simple.

A lot of nice JS frameworks blossomed lately - from shiny Backbone to Angular to Knockout - and they are going to get all the scene soon for sure. But sometimes I need a tradeoff solution between a full stack and the $ jungle of messed jQuery calllbacks - think about little enhancements to a basically plain html website like plugin setup, opening modals, handling simple client-side templating.

Long story short, I refactored Jason Garber implementation of Paul Irish idea, and here we are. Many thanks to John Resig's inheritance snippet as well.

* The stroke over the M stands for no model handling - stick with backbone.js & friends for it please!

Startup Events

Click Events

I am a bounded link

I am a bounded clickable element

Forms

Inspect the code and check the JS script at the end of this document source.

1. Import good ol' jQuery and the script:

<script src="//ajax.googleapis.com/ajax/libs/jquery/x.x.x/jquery.min.js"></script>
<script src="js/simple.js"></script>

2. Define controllers and actions [in a script tag or a separate file better]:

$(document).ready(function(){

  var router = new Router();
  router.setControllers({

    fooController : Controller.extend({

      fooAction : function(anElement){
        //your awesome code here
      },

      barAction : function(theElement){
        //your awesome code here
      },

    }),

    barController : Controller.extend({
      ...
    }),

    ...

  });

});					

3. Bind them to the DOM:

<a href="#" data-controller="fooController" data-action="barAction">I am bound to an action!</a>

That's it - all the <a/>, <button/>, <form/> are bound to a JS action if they feature a data-controller / data-action attribute pair: click events [or submit in the form case] are intercepted and the action is fired*.

Tip: you may also fire an action click-wise by binding it to a .clickable element of your choice.

You get a reference to the DOM element just clicked as the action parameter [anElement / theElement above] so you can interact with it - for example setting loading status, disabling a button, and so. Notice that when submitting a form, the whole form element is passed and not just the submit button.

* simple.js prevents default browser behavior.


Startup Actions

Sometimes you just need to execute an action on document load - for example the setup of a datepicker widget, or a picture carousel: you just add the data-startup attribute to the DOM element you're binding the action to:

<div id="myAwesomeWidget" data-controller="widgets" data-action="datepicker" data-startup></div>
...

widgets : Controller.extend({

  datepicker : function(widget){
    $(widget).someDatePickerPlugin( { ... } );
  },

...	

Et voilĂ , action is executed when page loads.

There is a default startup action in the Controller class that keeps track of the main DOM element it is tied to, so you can access to it later: such reference is stored in this._element inside the Controller.

awesomeWidget : Controller.extend({

  startup : function(widget){
    //You need to invoke the parent method in order to save the reference
    this._super(widget);
    
    // Your awesome widget setup here

  },

  selectAll : function(button){
    $('.awesomeItem', this._element).addClass('selected');
  },

  saveChanges : function(button){
	
    $(button).addClass('loading');

    $.post('path/to/resource', { foo : bar }, function(data){
      $(button).removeClass('loading');	
    });	

  },

...	

This is useful when you set up a widget and you need to reference to it again later, decoupling the logic from DOM selectors as much as possible. Of course you are going to perform DOM selections inside your actions, but you can narrow your scope to this._element:


Reusing Actions

What about firing actions inside other actions? Just call router.exec()* method:

...

someController : Controller.extend({

  someAction : function(trigger){
    router.exec('someOtherController', 'someOtherAction', trigger);
  },

...	

* router is the name you gave to the Router instance in your code.

Notice that you are passing a different trigger to the action by all chance: if you plan to reuse actions much, you are looking for wider solution for sure.


Denying Actions

Want to stop an element from triggering an action? Just give it the data-disabled attribute.

Let's say you want to disable the preview button once you submit a form:

...

  formAction : function(form){
	
    var self = this;
    $form = $(form);	
	
    $.post(
      $form.attr('action'),
      $form.serialize(),
      function(data){
			
        $('[data-action="preview"]', self._element).attr('data-disabled', true);
			
      }
    );
  },

...	

This way any action bound to our preview button won't be fired at all, without messing with such action's inner declaration.

Tip: Style data-disabled elements in order to reflect their behavior.


License

Copyright (c) 2012 Diego Caponera

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.