[英]using a DOM event callback inside an object
在p5.js中,如果DOM元素和函数都在同一个对象内,如何使DOM元素回调函数? 例如 :
function Snape()
{
this.myInput = createInput("");
this.myInput.changed(this.erase);
this.erase = function()
{
}
}
当我在this.myInput
键入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调用this.erase
(如建议的那样):
this.myInput.changed(function(){ myself.erase(); });
我收到相同的错误Uncaught TypeError: undefined is not a function
我尝试过所有不同可能性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
。
你必须保存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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.