我在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!" 可以在类声明中设置它.
默认情况下,setupController将model属性设置为路径挂钩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)
所以基本上,它是"初始化"控制器(设置模型和默认状态).
| 归档时间: |
|
| 查看次数: |
12529 次 |
| 最近记录: |