Guides

More

Controllers are the last part to the trinity of Spine and are very simple, being more of a set of conventions than actual code. Controllers are the glue inside your application, tying the various components together. Generally, controllers deal with adding and responding to DOM events, rendering templates and keeping views and models in sync.

Implementation

Controllers, like models, extend Spine.Module and so inherit all of its properties. This means you can use extend() and include() to add properties onto controllers, and can take advantage of all of Spine's context management. To create a controller, inherit a class from Spine.Controller.

The convention inside Spine is to give the controller a plural camel cased name of the model it is most associated with, in this case the Task model. Usually, you'll only be adding instance properties onto controllers, so you can add them inline just like any other class. Instantiating controllers is done by using the new keyword.

//= CoffeeScript
tasks = new Tasks

Every controller has an element associated with it, which you can access under the instance property el. This element is set automatically when creating a controller instance. The type of element created is specified by the tag property, which by default is "div".

events is an object in the following format {"eventType selector", "functionName"}. All the selectors are scoped to the controller's associated element, el. If a selector isn't provided, the event will be added directly on el, otherwise it'll be delegated to any children matching the selector.

Spine will take care of callback context for you, making sure it keeps to the current controller. Callbacks will be passed an event object, and you can access the original element the event was targeted on using event.target.

Since this is such a common scenario, Spine provides a helper, the elements property. This is in the format of {"selector": "variableName"}. When the controller is instantiated, Spine will go through elements, setting the appropriate elements as properties on the instance. Like with events, all the selectors are scoped by the controller's current element, el.