Angular控制器中popup属性莫名变为undefined问题求助
问题
我有一个小型Angular控制器,负责将模型绑定到UI,并通过Semantic UI处理弹窗的显示与隐藏逻辑。
export class MyController implements IController { popup: any | undefined onShow(context: any) { this.popup = $(context) console.log('this.popup', this.popup) } onHide() { this.popup?.popup('hide') } }
显示Semantic弹窗时功能正常,this.popup也成功存储了弹窗引用,控制台日志可查该引用。但点击关闭按钮触发onHide()方法时,this.popup却变为undefined。我已通过断点排查,确认Angular的构造函数及onChanges、onDestroy等生命周期钩子均未触发,为何明明已设置的this.popup会变为undefined?
补充信息:我们使用Semantic UI,以下是触发vm.onShow()的弹窗打开按钮(context为触发点击的按钮元素):
<button class="ui icon basic button" ng-class="{ yellow: !vm.model.allActive }" ng-click="vm.model.open(attribute.value)" jq-init-popup-fixed="{ inline: true, position: vm.model.position, on: 'click', onVisible: vm.onShow }"> <i class="icon semantic-icon filter" style="padding-left: 1px;"></i>
以下是触发onHide()的弹窗关闭按钮:
<div class="ui actions right floated button" ng-click="vm.model.close(); vm.onHide()"> <span translate="POPUP_BTN_OK"></span> </div>
分析与解决方案
核心原因:this指向异常
Semantic UI的onVisible回调执行时,上下文this并非控制器实例,导致你存储的popup并未真正挂载到控制器的this.popup属性上;或者后续调用onHide时,this指向错误,无法读取到正确的弹窗引用。解决办法1:构造函数绑定this
在控制器构造函数中,手动将回调方法的this绑定到控制器实例:export class MyController implements IController { popup: any | undefined constructor() { this.onShow = this.onShow.bind(this); this.onHide = this.onHide.bind(this); } onShow(context: any) { this.popup = $(context) console.log('this.popup', this.popup) } onHide() { this.popup?.popup('hide') } }解决办法2:使用箭头函数定义回调
箭头函数会自动继承外层上下文的this,直接用箭头函数定义onShow和onHide:export class MyController implements IController { popup: any | undefined onShow = (context: any) => { this.popup = $(context) console.log('this.popup', this.popup) } onHide = () => { this.popup?.popup('hide') } }额外验证点
可以检查弹窗关闭时是否触发了DOM元素销毁,但根据你反馈的生命周期钩子未触发,DOM应该仍存在,所以核心问题还是this指向异常。
内容的提问来源于stack exchange,提问作者Shiuyin
相关产品推荐
相关产品推荐

