javascript - 我希望根据当前路线将多个变量切换为 true 或 false

标签 javascript jquery ember.js controller handlebars.js

我希望根据当前路由将多个变量切换为 true 或 false, Controller 在页面加载时检查该路由。

VpcYeoman.SuperTableController = Ember.ArrayController.extend({  
    routedToLocations: false,
    routedToUsers: false,
    currentPath: '/',
    checkCurrentPath: function() {
      if ( currentPath == '/users')
        this.set( 'routedToUsers', true )
    } elsif ( currentPath == '/locations' ) {
        this.set( 'routedToLocations', true )
    }
});

superTable.hbs

{{#if routedToUsers}}
Users!
{{/if}}

{{#if routedToLocations}}
Locations
{{/if}}

在 users.hbs 中

{{render superTable model}}//这将产生字符串“Users!”

在locations.hbs

{{render superTable model}}//这将产生字符串“Locations!”

或者也许我可以在“用户” Controller 内部添加变量,例如routedToUsers,并设置值。它看起来像,

- users_controller.js -
    routedToUsers: true,
    canBeEdited: false,
    canBeDeleted: true,

这样,每个 super 表都具有这些变量,除非它们已经预定义了。另一个例子。

 - locations_controller.js - 
       routedToUsers: false, // this is obviously false but for example's sake
       routedToLocations: true,
       canBeEdited: false,
       canBeDeleted: false,

因此,如果我在另一个页面上单击 #link-to 将我路由到“用户”,则 Controller 将使用“checkCurrentPath”来确保我确实在用户页面上。

最佳答案

您的应用中实际上发生了两组主要的路径更改或“转换”。

首先: Ember 将初始化,路由器会将用户转换到所需的上下文。如果您有嵌套资源,这可能需要多次转换。如果用户返回嵌套资源或重新加载页面,Ember 很智能,会根据上下文重新加载。因此,自动转换。

第二:用户可以根据您设计的任何 UI 在应用程序中进行转换。

要解决两个问题中的第一个问题,您可能需要使用 setupController Hook 初始化每个路由的 Controller 以激活 currentPath 属性。这样,在页面加载时,路由将执行第一个 setter ,然后观察者将处理任何基于用户的路径更改。

这是一个通用路径观察器,您可以将其放置在应用程序 Controller 中。 它将解决两个问题中的第二个:

App.ApplicationController = Ember.Controller.extend({
  needs: ['super-table', 'users', 'locations'],
  currentPathDidChange: function () {
    var path_base = this.get('currentPath').split('.')[0];
    this.set('controllers.super-table.currentPath', path_base); // give your super table template the path
    this.nullifyActiveFlags(); // You can write this yourself...
    switch(path_base){ // just give me the base resource
      case 'users':
        this.set('controllers.users.activePath', true);
        break;
      case 'locations':
        this.set('controllers.locations.activePath', true);
        break;
    }
  }.observes('currentPath'),
//...

我可能会将回调逻辑从观察者中提取出来并放入其自己的方法中,但这只是显示可能性的伪代码。

您还应该将 super 表 currentPath setter 重构为 super 表 Controller 内的计算别名。

如果需要任何其他解释,请告诉我!我已经多次使用类似的模式,并且在正确配置时效果非常好。

关于javascript - 我希望根据当前路线将多个变量切换为 true 或 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24871938/

相关文章:

javascript - 如何在 react 中的一组元素中识别单个 div 元素?

javascript - JS + HTML5 : Uploading an audio blob via HTML form

jquery - 如何在li元素右侧顶部设置删除按钮?

ember.js - 仅当特定路线处于事件状态时,如何才能渲染 block ?

ember.js - 在 Ember 中处理网络连接和 promise 拒绝

javascript - Ember.在页面加载时选择空白,但选择了第一个选项

javascript - jQuery load() 和样式表不起作用?

javascript - 我的脚本似乎毫无理由地更改了一些值

javascript - 与 es6 类和 jquery 绑定(bind)

javascript - 未捕获的不变违规 : DetailPage. render()