2

假设我在微光中有一个简单的组件,其中包含项目列表

<todo-list @items={{ items }}></todo-list>

模板.hbs

<ul>
  {{#each @items key="@index" as |item|}}
    <li onclick={{ action clickme }}>{{ item }}</li>
  {{/each}}
</ul>

组件.ts

import Component, { tracked }  from '@glimmer/component';

export default class TodoList extends Component {
  constructor(options) {
    super(options);
  }
  clickme() {
     // how do I access the parent context from here?
  }
}

即使我从父母那里传递了一个动作

<todo-list @items={{ items }} @rootclickme={{ rootclickme }}></todo-list>

更新,template.hbs

<ul>
  {{#each @items key="@index" as |item|}}
    <li onclick={{ action @rootclickme }}>{{ item }}</li>
  {{/each}}
</ul>

在我的外部 component.ts

rootclickme () {
    // I don't have access to parent variables here either?
    // only what's within the scope of the function itself?         
}

我想要做的是有一个带有列表的组件。单击列表项时,我希望它在顶部弹出一个单击事件,以便父组件可以决定隐藏列表并显示此选定项的更详细视图。

我该如何在微光中做到这一点?在反应我会通过

注意:我没有使用完整的 ember.js,只是 glimmer.js 独立

4

2 回答 2

1

根据您的评论,您只能访问函数体中的内容,我怀疑action将操作绑定到子组件时缺少的帮助器正在使回调丢失它的this.

要解决它,请像这样绑定它:

<todo-list @items={{ items }} @rootclickme={{action rootclickme}}></todo-list>

我制作了一个示例游乐场,您可以查看。

于 2017-10-06T10:32:56.900 回答
0

我从 React 中学到的东西,也适用于我的 Glimmer 应用程序:你可以在构造函数中绑定你的函数。这样,当您将它们传递给不同的对象时,它们不会丢失它们的上下文。

export default class WhateverRootComponent extends Component {
  constructor(options) {
    super(options);
    this.rootClickMe = this.rootClickMe.bind(this)
  }
  rootClickMe() {
    console.log(this instanceof WhateverRootComponent)
  }
}

现在您可以像以前一样直接传递该函数,而无需使用额外的action帮助程序。

<!-- WhateverRootComponent template -->
<SomeChild @actionToTake={{ rootClickMe }} />

然后...

<!-- SomeChild template -->
<button onclick={{ action @actionToTake }}> Click Me </button>

单击时,控制台将记录true,因为该函数仍在父类的上下文中被调用。

于 2017-12-09T04:33:46.917 回答