【问题标题】:Closures in TypescriptTypescript 中的闭包
【发布时间】:2017-09-28 08:44:19
【问题描述】:

我有 Angular2/Typescript 网站。我正在为 CSS 使用 PrimeNG 框架。在我的网站中,我有 jQuery 完整日历。我想要实现的是点击事件时 - 出现模式。

在 AfterViewInit 接口方法中,我创建了如下的 fullClendar 对象:

  $("#calendar").fullCalendar({
   //..some properties
   eventClick: function (calEvent) {
                this.display = true;
    }

  })

display 是这个组件类的字段。当 display 设置为 true 时,应该出现模态 - 将其设置为 true 不会显示模态。

但是我在具有 onClick 处理程序的同一页面中有按钮

public showDialog() {
        this.display = true;
    }

单击按钮显示模式。

有HTML

<div class="ui-g dashboard" style="margin-top: -18px">

  <div class="ui-g-12 ui-md-12">
    <div class="card">
      <div id="calendar"></div>
    </div>
  </div>
</div>
<p-dialog header="Godfather I" [(visible)]="display" modal="modal" width="300" responsive="true">
  <p>dadsasd</p>
  <p-footer>
    <div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
      <button type="button" pButton icon="fa-close" (click)="display=false" label="No"></button>
      <button type="button" pButton icon="fa-check" (click)="display=false" label="Yes"></button>
    </div>
  </p-footer>
</p-dialog>
<button type="text" (click)="showDialog()" pButton icon="fa-external-link-square" label="Show"></button>

有什么问题?

【问题讨论】:

  • 您希望this 指的是什么?点击处理程序在没有this 绑定的情况下被调用,因此在草率模式下它将是全局对象(window),在严格模式下将是undefined
  • ajaja 没错,忘记了!!!

标签: jquery angular typescript closures


【解决方案1】:

Jquery 最有可能将 ID 为 #calendar 的元素设置为 this

您可以使用箭头函数来保持相同的上下文。

$("#calendar").fullCalendar({
  //..some properties
  eventClick: (calEvent) => {
    this.display = true;
  }

})

【讨论】:

  • Afff 没错,只是忘记了 abotut jQuery 这个关键字!
  • 这个关键字没有特殊的jquery,它是javascript,你可能想了解更多关于它的信息stackoverflow.com/questions/3127429/…
猜你喜欢
  • 2015-11-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多