I see many confusing examples in Ember.js official tutorials.
One example which I really don't like is:
App.ApplicationRoute = Ember.Route.extend({
setupController: function(controller) {
controller.set('title', "Hello world!");
}
});
App.ApplicationController = Ember.Controller.extend({
appName: 'My First Example'
});
Now as I understand it I could have written it like that instead:
App.ApplicationController = Ember.Controller.extend({
appName: 'My First Example',
title: 'Hello world!'
});
And removing the setupController
from route.
What is the purpose/benefit of using setupController
?
setupController (controller, model, transition) public By default, the setupController hook sets the model property of the controller to the specified model when it is not undefined . If you implement the setupController hook in your Route, it will prevent this default behavior.
This is the core feature of the Ember. js. The router used for to translate URL into the series of templates and also it represents the state of an application. The Ember. js uses the HashChange event that helps to know change of route; this can be done by implementing HashLocation object.
setupController
is primarily for setting up some controller context dynamically. In your example, if the title is always gonna be "Hello world!" it's fine to set it in class declaration.
By default, setupController
will set the model
property of controller
to the value returned from model
hook of the route.
You could also you it to, for example, set the model of another controller, or set some initial controller state that depends on the model.
For example, suppose you have the following:
// Model
App.Post = DS.Model.extend({
title: DS.attr('string'),
text: DS.attr('string'),
autoEdit: DS.attr('string')
});
// Controller
App.PostController = Ember.ObjectController.extend({
isEditing: null,
toggleEdit: function() { this.toggleProperty('isEditing'); }
});
Template:
<a href="#" {{action 'toggleEdit'}}>Toggle edit mode</a>
{{#if isEditing}}
{{input type="text" value=title placeholder="Title"}}
{{textarea type="text" value=text placeholder="Text"}}
{{else}}
<h1>{{title}}<h1>
<article>{{text}}</article>
{{/if}}
And then, you decide that it would be nice to turn editing mode on by default for posts with autoEdit
equal to true
. You'll probably want to do that in the route (since the controller, when instantiated, knows nothing about the model):
App.PostRoute = Ember.Route.extend({
setupController: function(controller, model) {
this._super(controller, model);
if (model.get('autoEdit')) {
controller.set('isEditing', true);
}
}
});
So basically, it's for "initializing" the controller (setting model and default state).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With