在对象内使用DOM事件回调

时间:2017-01-25 00:26:29

标签: javascript object events p5.js

在p5.js中,如果DOM元素和函数都在同一个对象中,如何使DOM元素回调成为函数?例如:

function Snape()
{
    this.myInput = createInput("");
    this.myInput.changed(this.erase);
    this.erase = function()
    {

    }
}

当我在this.myInput中输入内容时,我希望它能调用函数this.erase,但我收到错误11913: Uncaught TypeError: Cannot read property 'bind' of undefined

有可能吗? ------------------------------------------ 编辑:如果我在调用之前声明this.erase,主要问题就解决了:

function Snape()
{

    this.myInput = createInput("");
    this.erase = function()
    {

    }
    this.myInput.changed(this.erase);
}

但这是一个非常混乱的方式。

此外,我无法实现答案中建议的内容: 在p5.js中,我们调用回调的方式如下:

this.myInput.changed(this.erase);

如果我这样做

this.myInput.changed(this.erase());

我收到此错误:Uncaught TypeError: undefined is not a function

因此,当我尝试使用此this.erase时(如建议的那样):

this.myInput.changed(function(){ myself.erase(); }); 

我收到同样的错误Uncaught TypeError: undefined is not a function 我尝试了所有不同的可能性:

this.myInput.changed(function(){ myself.erase() }); 
this.myInput.changed(function(){ myself.erase; }); 
this.myInput.changed(function(){ myself.erase }); 

这些都不起作用。

我无法使用=>函数,因为我需要在对象的不同实例和多个DOM元素中多次调用this.erase

1 个答案:

答案 0 :(得分:0)

您必须将this保存到变量中,以便随后引用它:

function Snape() {
    var myself = this;
    this.myInput = createInput("");
    this.myInput.changed(function(){ myself.erase(); });
    this.erase = function()
    {
      console.log("erased");
    }
}

另一个(不太优雅)的解决方案是:

var input;

function setup () {
  createCanvas(500, 300);
  input = new Snape () ;
}

function Snape () {
    this.myInput = createInput("");
    this.myInput.changed(tunnel);
    this.erase = function()
    {
      console.log("erased");
    }

}

function tunnel () {
  input.erase();
}
相关问题