【问题标题】:Angular + PIXI - How to assign a component method to a variable and preserve 'this' referenceAngular + PIXI - 如何将组件方法分配给变量并保留“this”引用
【发布时间】:2019-04-12 01:03:37
【问题描述】:

我将 Angular 7 与 Pixi.js 4 一起使用。

为了从使用 PIXI.Graphics() 构建的图形元素中获取点击回调,我需要设置:

graphicElem.click = A_FUNCTION_REF

我已将我的函数定义为组件内的方法:

onClick(event: PIXI.interaction.InteractionEvent): void { console.log(this.myCompField); }

如果我写:

graphicElem.click = this.onClick;

我从控制台日志中得到:undefined。我认为因为this ref 没有通过,但这不是真的,我可以记录this 并且它不是未定义的。使用this.onClick.bind(this); 有效,但我读到不建议使用bind()

正确的方法是什么?我错过了什么?

【问题讨论】:

    标签: angular typescript pixi.js angular7


    【解决方案1】:

    在这种情况下,您可以使用箭头函数语法而不是 .bind

    试试这个:

    onClick = (event: PIXI.interaction.InteractionEvent) => { console.log(this.myCompField); }
    

    【讨论】:

    • 但是我不想内联我的函数,我想使用我的组件类的方法。
    • @EduBic,有什么具体原因吗?另外,说不推荐使用.bind(this),有什么具体原因吗?
    • here。搜索 bind 和 angular 我发现了这个相关的 issue,也许在这种情况下 bind 是唯一的方法,或者你可以使用内联函数作为你的建议。
    • 是的。顺便说一句,如果您定义自定义验证器,通常也会使用绑定。所以说不推荐是不对的。顺便说一句,您为什么不想以内联方式执行此操作?
    • 函数的大小可能会增长。无论如何,您的解决方案是有效的替代方案,实例函数保留正确的 this 引用。这也带来了组件中声明的方法之间的一致性问题。
    猜你喜欢
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 2021-05-16
    • 1970-01-01
    • 2016-05-12
    • 2014-09-07
    相关资源
    最近更新 更多