【问题标题】:Triggering an action on the parent route from a component in the sub route从子路由中的组件触发对父路由的操作
【发布时间】:2019-02-15 14:42:55
【问题描述】:

在我的应用程序中,我目前有一个父路由来管理我的查询参数。我有一个使用关闭操作重置这些参数的组件。当前的实现工作,看起来像这样:

// Component

import Component from '@ember/component';

export default Component.extend({
  tagName: '',
  actions: {
    actionTest() {
      this.get('onClick')()
    }
  }

});


  <div class="text-muted" style="cursor: pointer" {{action "actionTest"}}><small>{{text}}</small></div>

// Parent Route Controller

import Controller from '@ember/controller';

export default Controller.extend({

  actions: {
    resetAllParams() {
      this.set('param1', null)
      this.set('param2', null)
    }
  }

});

// Template

{{reset-params-button onClick=(action "resetAllParams") text="Reset Filters" size="xs"}}

我想将组件从父路由模板移动到子路由模板。当我这样做时,我不再能够重置参数 - 我的理解是不可能在子路由上操作父路由的参数。

我认为我需要在关闭操作功能中增加一个步骤,但我不太了解它。我尝试使用Ember Route Action Helper,但这似乎不适合这个用例。

我尝试通过添加以下内容来“冒泡”该操作:

  // Sub-Route Template

{{reset-params-button onClick=(action "resetAllParams") text="Reset Filters" size="xs"}}

// Sub Route Controller

import Controller from '@ember/controller';

export default Controller.extend({
resetAllParams(){}
});

但它在组件控制器中的操作中出现“this.get is not a function”错误。

非常感谢任何帮助

【问题讨论】:

  • 将操作提取到服务中,然后使用该服务:)

标签: ember.js


【解决方案1】:

您可以将父级的路由控制器注入到子级的路由控制器中。在孩子的路由控制器中:

@import Controller, { inject as controller } from '@ember/controller';

export default Controller.extend({
  parent: controller(), // use actual name of parent route controller

  actions: {
    resetAllParams() {
      this.get('parent').send('resetAllParams');
    }
  }
});

希望这会有所帮助。有关注入的更多信息,请参阅https://guides.emberjs.com/v3.4.0/applications/dependency-injection/#toc_ad-hoc-injections

【讨论】:

  • 我永远不会想到注入控制器。我认为我的应用程序中的其他地方也可以从中受益。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2018-03-24
  • 2016-07-06
  • 2018-03-09
  • 1970-01-01
  • 2016-09-04
  • 2023-04-04
  • 2022-07-24
  • 2016-12-19
相关资源
最近更新 更多