【问题标题】:How to create a subnav in ember.js如何在 ember.js 中创建子导航
【发布时间】:2013-08-29 18:04:02
【问题描述】:

这个问题困扰了我好几天。当用户访问“关于”页面时,我需要在应用程序模板的主导航下显示一个子导航。我觉得我一定错过了一些重要的概念,因为我一直在阅读,如果在 Ember 中做某件事非常困难,那么你可能做错了。而且我觉得 Ember 应该能够轻松处理简单的子导航。

当单击“关于”时,我希望子导航显示在主导航下方的细白水平条上。

由于导航代码在应用程序模板中,我无法将子导航放在 about 模板中。

我的路由器:

App.Router.map(function() {
  this.resource("about", function() {
    this.route("philosophy");
    this.route("leadership");
    this.route("staff");
    this.route("affiliations");
  });

  this.route("conditions");
  this.route("programs");
  this.route("testimonials");
});

我无法在应用程序模板中呈现部分内容,因为我只想在有人位于 /about url 时显示它。

我尝试过简单的旧 jQuery 显示和隐藏:

App.ApplicationController = Ember.ObjectController.extend({
  currentRouteChanged: function() {
    if(this.get('currentRouteName').indexOf('about') > -1) {
      $("ul").removeClass("sub-nav-list-hide");
      $("ul").addClass("sub-nav-list-show");
    }
  }.observes('currentRouteName')
});

当你点击 about 时它会起作用,但是当你点击后退按钮或导航到另一个页面时 subnav 不会隐藏。

我被困住了,我觉得我这样做太难了。

【问题讨论】:

    标签: javascript ember.js handlebars.js


    【解决方案1】:

    我会在 App.AboutRoute 中的应用程序控制器中设置一个属性

    App.AboutRoute = Ember.Route.extend({
      activate: function(){
        this.controllerFor('application').set('renderAboutSubNav', true);
      },
      deactivate: function(){
        this.controllerFor('application').set('renderAboutSubNav', false);
      }
    });
    

    然后检查应用程序模板中的属性。

    {{#if renderAboutSubNav}}
      {{render 'about/subnav'}}
    {{/if}}
    

    这是一个例子jsbin

    【讨论】:

    • 非常感谢!这正是我想要的!如果您不介意解释一下 App.AboutRoute 中发生了什么?
    • activatedeactivate 是路由器进入和退出路由时执行的两个钩子。
    【解决方案2】:

    这对我来说看起来很优雅!

    我们可以在应用控制器中做类似的事情。

    App.ApplicationController=Ember.Controller.extend({
        renderAboutSubNav:function(){
            var reg = new RegExp("^about\.");
            return reg.test(this.get('currentPath'));
         }.property('currentPath')
    
    });
    

    【讨论】:

    • 在控制器和路由中做这件事的主要区别或优点/缺点是什么?
    猜你喜欢
    • 2014-01-17
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2016-03-26
    • 2018-04-07
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    相关资源
    最近更新 更多