![](/img/trans.png)
[英]$emit an event from child to parent in vue.js, es6 syntax
[英]In Node/raw ES6, how could I emit an event from a parent class and trigger an event in the child class from their respective constructors?
我目前正在研究 exercism.io 的“JS 軌道 - 反應項目”(不,不是反應)。 練習是讓類對彼此的行為做出反應。 我不確定繼承是否是最好的選擇,但我覺得它就像我要得到的一樣接近。 (PS 這是我在這里的第一篇文章,在決定在這里問我的第一個問題之前,我嘗試了很多地方。('PPS')=> '你好' :)
`class InputCell extends EventEmitter {
constructor(value) {
super(value);
this.value = value;
}
setValue(value) {
this.value = value;
// I'm assuming this emitter doesn't leave the scope of the object it creates?
this.emit('cellChange');
}
}
class ComputeCell extends InputCell {
constructor(cells, compute) {
super(cells, compute);
this.value = compute(cells);
// super wasn't my first choice, but 'this' didn't work either
super.on('cellChange', () => compute(cells));
}
}`
編輯 - 抱歉,這是我運行的失敗測試。
` test('compute cells update value when inputs are changed', () => {
const inputCell = new InputCell(1);
const computeCell = new ComputeCell(
[inputCell], inputs => inputs[0].value + 1
);
inputCell.setValue(3);
expect(computeCell.value).toEqual(4);
});
`
@TJ Allen:我被困在同一個練習中,但我找到了解決方案頁面:https ://exercism.io/tracks/javascript/exercises/react/solutions
花了一些時間,但我發現這個解釋對於我的理解來說足夠簡單(特別是對於您發布的測試用例):
export class InputCell {
constructor(value) { // test 1: accepts input
this.value = value;
}
setValue(value) {
this.value = value; // test 2: allows input value to be set
}
}
export class ComputeCell {
constructor(inputCells, func) { // test 3: allows setting compute cells
this.inputs = inputCells;
this.func = func;
}
get value() {
return this.func(this.inputs); // test 5: compute cells update value when inputs are changed
}
}
對於其他 exercism.io 用戶,請注意我遺漏了測試 4的評論:計算單元以正確的順序獲取輸入,因為它與此處提出的問題不太相關。
編輯:就個人而言,我認為特定測試 5 案例的措辭含糊不清且令人困惑。
“當輸入改變時計算單元更新值”
哪些輸入和在哪里? 這聽起來像是要求您使用某種事件偵聽器,以便InputCell
內的值自動觸發ComputeCell
內的值發生更改 - bc 我也這么認為。
但是看看測試,我認為他們實際上要求的是:如果您用一個數字初始化InputCell
的新實例並將該實例作為參數傳遞以創建ComputeCell
的新實例,那么您的新ComputeCell
實例將已更新它的value
(通過 getter)基於您傳遞給它的InputCell
實例的value
。 如果測試消息記錄了以下內容,則可能會更清楚:
“當用新輸入調用時,計算單元返回不同的值”
仍然可能沒有我想要的那么清楚,但不那么誤導海事組織。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.