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 template.hbs
- {{#each @items key='@index' as
Solution 1:
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={{actionrootclickme}}></todo-list>
I have made an example playground that you can check out.
Solution 2:
Something I learned from React, that works in my Glimmer app as well: you can bind your functions in the constructor. That way, when you pass them around to different objects, they won't lose their context.
exportdefaultclassWhateverRootComponentextendsComponent {
constructor(options) {
super(options);
this.rootClickMe = this.rootClickMe.bind(this)
}
rootClickMe() {
console.log(thisinstanceofWhateverRootComponent)
}
}
Now you can pass that function in directly as you were doing before, without using the extra action
helper.
<!-- WhateverRootComponent template --><SomeChild @actionToTake={{rootClickMe }} />
then...
<!-- SomeChild template --><buttononclick={{action @actionToTake }}> Click Me </button>
When clicked, the console will log true
because the function still is being called in the parent class's context.
Post a Comment for "How Do I Get The Parent Context From Within A Component In Glimmer?"