从子路由中的组件触发父路由上的操作

Triggering an action on the parent route from a component in the sub route

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

// 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 但这似乎不适合此用例。

我尝试通过添加以下内容来 'bubble up' 操作:

  // 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' 错误而出错。

非常感谢任何帮助

您可以将 parent 的路由控制器注入 child 的路由控制器。在 child 的路由控制器中:

@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