O'Reilly logo

JavaScript Web Applications by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Controllers

Controllers are the last component to Spine, and they provide the glue that will tie the rest of your application together. Controllers generally add event handlers to DOM elements and models, render templates, and keep the view and models in sync. To create a Spine controller, you need to subclass Spine.Controller by calling create():

jQuery(function(){
  window.Tasks = Spine.Controller.create({
    // Controller properties
  });
});

It’s recommended to load controllers only after the rest of the page has loaded, so you don’t have to deal with different page states. In all the Spine examples, you’ll notice each controller is contained inside a call to jQuery(). This ensures that the controller will be created only when the document’s ready.

In Spine, the convention is to give controllers camel-cased plural names—usually, the plural of the model with which they’re associated. Most controllers just have instance properties, as they’re used after instantiation only. Instantiating controllers is the same as instantiating any other class, by calling init():

var tasks = Tasks.init();

Controllers always have a DOM element associated with them, which can be accessed through the el property. You can optionally pass this through on instantiation; otherwise, the controller will generate a default div element:

var tasks = Tasks.init({el: $("#tasks")});
assertEqual( tasks.el.attr("id"), "tasks" );

This element can be used internally to append templates and render views:

window.Tasks = Spine.Controller.create({ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required