Ember.js Controllers for the absolute beginner
Controllers:
There are three types of controllers you can define:
- Controller: "No Instances of a Model"
strictly for managing binding propeties and state in an easy way between the view and the controller.
- ObjectController: "One Instance of a Model"
Intends to be populated by a single model, which is available via {{this}} in templates for displaying content.
- ArrayController: "Many Instances of like Models"
Expects an array of objects as it's backing model, available as in an object controller. Special shortcuts exist for iterating through the array's backing context such as {{#each}}.
Simple Guidelines
Controllers contain properties, computed properties, observables, as well as event lifecycle binding via the .on() decorator for functions. e.g;
actions: {
toggleWidget: function (args) {
// do things
}.on('SomeViewClass.didTransition')
}
Controllers, like Routes, can contain an object named 'actions' that allow you to handle state change between the backing model and it's presentation.
actions: {
name: function (model) {
// do things
}
}
Actions can be invoked by calling {{action 'name' this}}.
Defining a 'name' action within the object as a function would receive the backing model's instance via the 'this' after the action name, if you include it.
Controllers should generally be used as state - for example, the active tab of a three tab widget- for views. View and Controllers are 1:1 - every view has a controller - generated or otherwise.
Controllers do not render their own template, though can call an action (via an {{action}} in the template) parent (or presenting) route. Actions bubble up from controllers to routes. if not defined on the controller.
Controllers that are backed by a model - for example, by setting the .model object (you may see controller.content interchangeably here- this is okay, they set the same thing) are populated with their model(s) during the corresponding Route's setupController(model, controller) hook.
Controllers that use Object or ArrayControllers should have their presenting route's model() hook fetch or otherwise create and return the model for the Controller.
Controllers should not have shared or public state. Keep them brief, keep them presentational.
Controller actions should not be used to modify models. define those kinds of actions on the presenting route so that the controller can be updated or rerendered without concern.
A Controller and View are 1:1, but a Template contains only html, and any views as inserted with the {{view}} helper, or the {{#view}}{{/view}} helper.
A Controller action should be what is called when a View's specific event is captured. (mousedown, touchStart, click, and so forth)
Written by Landon Noss
Related protips
1 Response
As someone who just joined an Ember project, thank you!