如何从glimmer中的组件中获取父上下文? [英] How do I get the parent context from within a component in glimmer?
问题描述
比方说,我在微光中有一个简单的项目列表
Let's say I have a simple component in glimmer with a list of items
<todo-list @items={{ items }}></todo-list>
template.hbs
template.hbs
<ul>
{{#each @items key="@index" as |item|}}
<li onclick={{ action clickme }}>{{ item }}</li>
{{/each}}
</ul>
component.ts
component.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?
}
}
即使我从父母那里传递了一个动作
Even if I pass in an action from the parent
<todo-list @items={{ items }} @rootclickme={{ rootclickme }}></todo-list>
已更新template.hbs
updated, template.hbs
<ul>
{{#each @items key="@index" as |item|}}
<li onclick={{ action @rootclickme }}>{{ item }}</li>
{{/each}}
</ul>
在我的外部组件中.ts
in my outer component.ts
rootclickme () {
// I don't have access to parent variables here either?
// only what's within the scope of the function itself?
}
我想做的是有一个带有列表的组件.单击列表项时,我希望它使单击事件冒泡到顶部,以便父组件可以决定隐藏列表并显示此选定项的更详细视图.
What I'm trying to do is have a component with a list. When a list item is clicked, I want it to bubble up a click event to the top, so that the parent component can decide to hide the list and show a more detailed view for this selected item.
我该如何在微光下做到这一点?在反应中,我会通过
How do I go about doing this in glimmer? In react I'd be passing
注意:我没有使用完整的ember.js,而是单独使用glimmer.js
Note: I'm not using full ember.js, just glimmer.js standalone
推荐答案
根据您的评论,您只能访问函数体内的内容,我怀疑是在绑定函数时缺少 action
帮助器.对子组件的操作会使回调失去其 this
.
By your comment that you only have access to what's in the function body, my suspicion is that the missing action
helper when binding the action to the child component is making the callback lose its this
.
要解决此问题,请像这样将其绑定:
To address it, bind it in like this:
<todo-list @items={{ items }} @rootclickme={{action rootclickme}}></todo-list>
我已一个例子游乐场可以检查出来.
这篇关于如何从glimmer中的组件中获取父上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!