【问题标题】:How do I maintain the 'correct' scope in javascript even listeners?如何在 javascript 甚至监听器中保持“正确”范围?
【发布时间】:2015-01-23 01:04:55
【问题描述】:

我正在使用 Typescript 编写几何引擎,并且正在尝试实现拖放。我有一个从几何对象继承的点对象,它可以控制svg 元素内的circle 元素。我有一个mousedown even 监听器附加到调用属于点对象的函数的圆元素,有点像这样:

class point extends geometry {
    htmlNode:any;
    constructor() {
        this.htmlNode = makeTheThing();
        addItToTheDom();
        this.htmlNode.addEventListener("mmousedown",this.onClick);
        onClick();
    }

    onClick() {
        console.log(this);
    }
}

当页面加载时,它会将点对象输出到控制台,但是当我单击它时,它会输出 html 元素,而不是 javascript 对象。以前我是这样解决的:

class point extends geometry {
    htmlNode:any;
    constructor() {
        this.htmlNode = makeTheThing();
        addItToTheDom();
        var blah = this;
        var f = function() {
            console.log(blah);
        }
        this.htmlNode.addEventListener("mmousedown",f);
        f();
    }

    onClick() {
        console.log(this);
    }
}

那会在加载和单击时给出 javascript 对象,但它很难看,我想做得更干净。

更新:对于任何关心的人,我最终只是重写了这个,现在更漂亮了。

【问题讨论】:

  • 试试this.htmlNode.addEventListener("mmousedown",f.bind(this));。不过,this 可能又被分配给了 htmlNode。
  • @Halcyon 这很有效,而且更漂亮,但我也觉得有点老套,我会一直使用它,直到找到更好的东西
  • 所以,默认情况下,事件回调中的this会被设置为处理事件的DOM节点。你必须决定你想要this 是什么。如果这是您想要的,那么您可以在分配事件处理程序之前将this 保存到范围内的局部变量中,以便您可以通过这种方式访问​​该值。如果您希望this 成为您自己的对象,则使用.bind() 自行设置。这是两个主要选项。

标签: javascript typescript


【解决方案1】:

在纯 JavaScript (ES5) 中,您可以使用 bind 创建一个新函数,该函数将永久绑定函数上下文 (this):

this.htmlNode.addEventListener("mmousedown",this.onClick.bind(this));

在 TypeScript 中(很快在 ES6 中)我们有箭头函数:

this.htmlNode.addEventListener("mmousedown", event => this.onClick(event));

箭头函数维护一个词法this,即从周围上下文中获取this。

【讨论】:

  • 我已经用这种技术破解了一个相当糟糕的解决方案,我确信让这项工作正常工作的唯一方法是对我的程序进行全面重组。我需要学习一些真正的 OOP...
【解决方案2】:

在纯js中我会这样做(当然没有'class'^^):

class point extends geometry {
var parent = this;
var htmlNode = null;
this.constructor = function() {
    parent.htmlNode = makeTheThing();
    parent.htmlNode.addEventListener(yourStuff);
}

this.onClick = function() {
    console.log(parent);
}

}

也许ts中有更好的方法,但这应该可以工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多