【问题标题】:Ember unable to pass route action to componentEmber 无法将路由操作传递给组件
【发布时间】:2017-01-31 14:59:22
【问题描述】:

我有一个组件需要接收我放置在路由上的操作,因为它的工作是刷新模型的一部分。

显然我可以从按钮调用路由操作,但我无法将相同的操作传递给组件。

路由器

export default Ember.Route.extend({
    actions: {
        doSomething: function(){
            alert('Router handled!');
        }
    }
});

页面模板

<button {{action "doSomething"}}>speak</button>
{{myComponent onGetUsers=(action "doSomething")}}

组件

export default Ember.Component.extend({
    actions: {
        onPageClicked: function(pageNo){
            this.sendAction('onGetUsers', pageNo);
        }
    }
});

按钮点击有效。当我使用该组件时,我会执行它的操作,但 sendAction 永远不会工作或触发。

是否存在不能将操作传递给下线组件的规则?还是我在代码中做错了什么?

【问题讨论】:

  • 我能够通过使用控制器上的操作来触发路由器,方法是使用 this.send() 而不是 this.sendAction() 但我仍然想知道为什么将路由器操作发送到该组件不起作用。如果可能的话。

标签: ember.js


【解决方案1】:

sendActions - 可用于组件间通信。
send - 可用于控制器路由通信。 你不能使用任何一种方式。

对于组件路由通信,你可以使用下面的插件。

ember install ember-route-action-helper

通过在路由中定义action,可以从template.hbs中调用

<button {{action (route-action 'appRouteAction' 'fromApplication.hbs') }}>button</button>

你可以从 my-component.hbs 调用

<button {{action (route-action 'appRouteAction' 'from MyComponent.hbs') }}>My-Component button</button>

如果你想先调用组件动作,再调用路由中的动作,

在 template.hbs - 包含带有路由动作的组件作为关闭动作,

{{my-component2 appRouteAction=(route-action 'appRouteAction')}}

在 my-compoent2.hbs 中,

<button {{action 'appRouteAction' 'CallFromComponentActions-my-compoent2.hbs' }}>CallFromComponentActions</button>

在 my-compoent2.js 中

import Ember from 'ember';
export default Ember.Component.extend({
  actions:{
    appRouteAction(fromWhere){
      console.log('appRouteAction in my-component ');
      this.get('appRouteAction')(...arguments);
    }
  }
});

Sample Twiddle- 玩转 ember-route-action-helper-addon。

【讨论】:

  • 如果能移到 ember core 就好了
【解决方案2】:

sendAction 是一个古老的概念。它仍然有效,但它基本上已被您似乎知道的关闭操作所取代。

它目前不适用于路由操作的原因是因为试图为未知目标创建闭包。在将模板插入 DOM 时,闭包操作会尝试识别确切的函数并在调用时触发它。这样做是为了简单起见,以便操作可以返回一个值。当该操作在控制器或父组件上时,这很容易。当该动作在路线上时,这并不容易,因为它必须遍历路线链才能找到执行该动作的最近路线。此外,由于路由操作可以返回 false 以允许操作进一步冒泡,因此完全支持会很棘手。

有一个 ember-cli 插件可以帮助弥补这一差距。结帐:https://github.com/DockYard/ember-route-action-helper。这是一个展示它的 JSBin:http://jsbin.com/luruyegice/edit?html,js,output

【讨论】:

  • 是的,我想我对关闭操作很熟悉 :-) 只是没有被淘汰。我错误地认为它们会在不可用的地方可用。这是一个很好的解释,但在此之前的答案实际上用一个解决方案回答了这个问题,所以我觉得我必须接受它。不过,我确实想感谢你。谢谢。
  • 我想我更多的是回答你添加到问题中的评论,而不是问题本身。只是想在这里提供一些背景和解决方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-20
  • 2020-02-06
  • 1970-01-01
  • 1970-01-01
  • 2017-02-05
  • 1970-01-01
相关资源
最近更新 更多