【问题标题】:EventEmitter: simultaneous events blend, how to prevent this?EventEmitter:同时发生的事件混合,如何防止这种情况?
【发布时间】:2016-09-19 06:47:50
【问题描述】:

在一个父组件中接收来自多个子组件的事件 我将事件通道从父组件(ProjectsComponent)传递到每个子组件(ProjectHeaderComponent)

projects.component.ts

  projects: Project[];
  editing = false;
  channel: EventEmitter<boolean>;

  constructor(private projectService: ProjectService) {
    this.channel = new EventEmitter<boolean>(false);
    this.channel.subscribe(isEditing => {
      this.editing = isEditing;
      console.log(this.editing);
    });
  }

projects.component.html

<div *ngFor="let project of projects">
    <project-header [project]="project" [isEditing]="channel"></project-header>
</div>

project-header.component.ts

  @Input() project: Project;
  @Input() isEditing: EventEmitter<boolean>;

  set editing(data: boolean) {
    //....
    this.isEditing.emit(this._editing);
  }

project-header.component.html

<input type="text" (click)="toggleEditing()">

但如果我已经在一个输入上并单击另一个,事件混合,我收到true, false,而不是false, true

我试图用setTimeout(() =&gt; this.editing = isEditing, 0); 包裹this.editing = isEditing;,但这不起作用。

【问题讨论】:

  • 当我们不知道editing 使用的属性在哪里时,很难给出任何建议。否则,这段代码对我来说很好,应该可以按你的意愿工作(如果我理解正确的话)。
  • 谢谢你,@Martin,用 setTimeout 在调用堆栈底部添加打开事件,因为答案看起来很好,我停在这,谢谢)

标签: javascript angular


【解决方案1】:

其中一个技巧——关于 open 的事件必须在 close 之后到达

  set editing(data: boolean) {
      /*on close*/
      if (!this._editing) {
        this._editedService.changeEdited(this._editing);
      } else /*on open*/ {
        setTimeout(() => this._editedService.changeEdited(this._editing), 0);
      }
  }

【讨论】:

    猜你喜欢
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    相关资源
    最近更新 更多