gpt4 book ai didi

javascript - 如何将对象属性函数变成事件发射器?

转载 作者:行者123 更新时间:2023-11-28 18:38:30 24 4
gpt4 key购买 nike

这是 this 的后续内容关于组件之间的函数引用的问题。

如果我有一个ParentComponent:

export class ParentComponent {
public myParentVariable = 'Hello world';

test() {
console.log(this.myParentVariable);
}

public options: any[] = [
{label: 'Item 1', onClick: this.test},
{label: 'Item 3', onClick: this.test},
{label: 'Item 6', onClick: this.test},
{label: 'Item 2', onClick: this.test}
];
}

如您所见,我在 onClick 属性中传递了对 test 的引用。

然后我有一个 ChildComponent,我将 optionsParentComponent 传递给它:

<child [options]="options"></child>

child 中我有一个列表:

<ul class="dropdown-list">
<li *ngFor="#option of options" (click)="option.onClick()"></li>
</ul>

正如您在模板中看到的那样,我随后将之前的 onClick 调用为 (click)="option.onClick()"

现在的问题是,从这里开始,它不再知道 this.myParentVariable 是什么,因为我们只是传递对 test 的引用。因此,我想将 onClick 放入 EventEmitter 中,然后我可以调用 .emit() ,以便我们执行 test 具有正确的数据绑定(bind),如所示 here .

但是由于我传递了一个包含对象的数组,该对象包含引用函数的属性,所以我不太确定如何使每个对象的单个 onClick 属性成为 EventEmitter.

我尝试将整个 options 制作成输出的 EventEmitter 但惨败。

关于如何实现这一目标有什么想法吗?

最佳答案

JavaScript 中的

this 关键字取决于上下文。在大多数情况下,this 的值由函数的调用方式决定。由于 TypeScript 是 JavaScript 的类型化超集,因此其行为相同,请点击下面的链接。

ECMAScript 5 introduced Function.prototype.bind. Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.

function's this keyword , bind method

您还可以使用箭头函数作为替代。

关于javascript - 如何将对象属性函数变成事件发射器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36557154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com