2017-10-06 31 views
1

比方說,我在一線的簡單組件與項目的列表如何從閃爍的組件中獲取父上下文?

<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獨立

+0

當你在綁定動作時,它應該是'@rootclickme = {{action rootclickme}}'。使用'action'助手可以確保回調函數'this'綁定到正確的組件。 – locks

+0

你似乎也削減了你的帖子? 「在反應中,我會通過」。 – locks

回答

1

通過您的評論,你只能訪問什麼函數體中,我懷疑是綁定到子組件的行動時失蹤action正在使回調失去其this

爲了解決它,在結合這樣的:

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

我已經an example playground,你可以查出來。

+0

這爲我工作。謝謝! – hsugar

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因爲功能仍然是被稱爲在父類的上下文。