假设我有一个简单的glimmer组件,它包含一个项目列表
<todo-list @items={{ items }}></todo-list>template.hbs
<ul>
{{#each @items key="@index" as |item|}}
<li onclick={{ action clickme }}>{{ item }}</li>
{{/each}}
</ul>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?
}
}即使我从父母那里传递了一个动作
<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独立的
发布于 2017-10-06 10:32:56
根据您的评论,您只能访问函数体中的内容,因此我怀疑,在将操作绑定到子组件时缺少的action助手正在使回调失去其this。
要解决这个问题,请按如下方式绑定:
<todo-list @items={{ items }} @rootclickme={{action rootclickme}}></todo-list>我做了一个例子操场,你可以退房。
发布于 2017-12-09 04:33:46
我从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,因为函数仍在父类的上下文中调用。
https://stackoverflow.com/questions/46603065
复制相似问题