Canttouchit
Canttouchit

Reputation: 3159

Ember.js What is the difference between the setupController and declaring a <Name>Controller

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?

Upvotes: 14

Views: 14567

Answers (1)

Gosha A
Gosha A

Reputation: 4570

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).

Upvotes: 23

Related Questions