Ember - Setting homepage title in controller or route?

送分小仙女□ 提交于 2019-12-24 13:18:35

问题


What is the best practice?

This is my HTML:

<script type="text/x-handlebars">
    <div id="top-panel">
        <h1>{{title}}</h1>
    </div>
    <div id="wrapper">
        <div id="content">
            {{outlet}}
        </div>
    </div>
</script>

Where should I set {{title}}? I found out there are two ways to do this...

First:

App.ApplicationRoute = Ember.Route.extend({
    setupController: function (controller) {
        controller.set("title", "Foo Bar")
    }
});

Second:

App.ApplicationController = Ember.ObjectController.extend({
    title: "Hello World"
});

Which one is a recommended way of doing this?


回答1:


If it's just a static thing that will never change, I'd put it in the second, or just in the handlebars template.

Additionally

  1. since you aren't setting an object on the application controller, it doesn't really need to extend the ObjectController, you can just extend Controller.

    Ember.ObjectController is part of Ember's Controller layer. It is intended to 
    wrap a single object, proxying unhandled attempts to get and set to the 
    underlying content object, and to forward unhandled action attempts to its target.
    
  2. In the future, if you are overriding the setupController it's usually recommended to call this._super(controller, model) like:

    setupController: function (controller, model) {
       this._super(controller, model)
       controller.set("title", "Foo Bar")
    }
    

setupController's default implementation is to set the content on the controller, so technically it makes no difference that you aren't calling super.

In the case of a dynamic title, I'd make it a computed property:

 App.ApplicationController = Ember.ObjectController.extend({
     title: function(){
        var currentdate = new Date(),
            title = "Awesome Title: " + currentdate.getDate() + "/"
            + (currentdate.getMonth()+1)  + "/" 
            + currentdate.getFullYear() + " @ "  
            + currentdate.getHours() + ":"  
            + currentdate.getMinutes() + ":" 
            + currentdate.getSeconds();

          return title;
     }.property()
 });


来源:https://stackoverflow.com/questions/19446361/ember-setting-homepage-title-in-controller-or-route

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!