Ember.js setupController和声明<Name> Controller之间有什么区别

Can*_*hit 12 ember.js

我在Ember.js官方教程中看到了许多令人困惑的例子.

我真的不喜欢的一个例子是:

App.ApplicationRoute = Ember.Route.extend({
    setupController: function(controller) {
        controller.set('title', "Hello world!");
    }
});

App.ApplicationController = Ember.Controller.extend({
    appName: 'My First Example'
});
Run Code Online (Sandbox Code Playgroud)

根据我的理解,我可以像这样写它:

App.ApplicationController = Ember.Controller.extend({
    appName: 'My First Example',
    title: 'Hello world!'
});
Run Code Online (Sandbox Code Playgroud)

并删除setupController路线.

使用的目的/好处是setupController什么?

Gos*_*ich 22

setupController主要用于动态设置某些控制器上下文.在你的例子中,如果标题总是"Hello world!" 可以在类声明中设置它.

默认情况下,setupControllermodel属性设置为路径挂钩controller返回的值model.

例如,您也可以设置另一个控制器的模型,或设置一些取决于模型的初始控制器状态.

例如,假设您有以下内容:

// 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'); }
});
Run Code Online (Sandbox Code Playgroud)

模板:

<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}}
Run Code Online (Sandbox Code Playgroud)

然后,您决定默认情况下打开编辑模式对于autoEdit等于的帖子会很好true.您可能希望在路径中执行此操作(因为控制器在实例化时对模型一无所知):

App.PostRoute = Ember.Route.extend({
  setupController: function(controller, model) {
    this._super(controller, model);
    if (model.get('autoEdit')) {
      controller.set('isEditing', true);
    }
  }
}); 
Run Code Online (Sandbox Code Playgroud)

所以基本上,它是"初始化"控制器(设置模型和默认状态).

  • 请注意,`isEditing`不在**模型**中(它不需要保持),它在控制器上.`isEditing`只是保持当前**控制器**的一些状态,即编辑模式是打开还是关闭.你链接的例子只是改变了一些**model**属性,当然也没有涉及控制器状态. (4认同)