2017-01-25 4 views
0

p5.jsでは、DOM要素と関数の両方が同じオブジェクト内にある場合、どのようにDOM要素コールバックを関数にしますか?例えば:私はthis.myInputで何かを入力するとオブジェクト内でDOMイベントコールバックを使用する

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

    } 
} 

、私はそれが機能this.eraseを呼び出すしたいと思いますが、私はエラー11913: Uncaught TypeError: Cannot read property 'bind' of undefined

を得ることが可能ですか? ------------------------------------------ 編集:主な問題は次のとおりです。

function Snape() 
{ 

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

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

が、それはそれを行うには本当に厄介な方法です:私はそれを呼び出す前に、私はthis.eraseを宣言した場合に解決。私はこの

をすれば

this.myInput.changed(this.erase); 

:私たちは、コールバックを呼び出す方法がこのようなものです、p5.jsで を:

はまた、私は答えに提案されたものを実装することができませんでした

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

私はこのエラーを取得する:Uncaught TypeError: undefined is not a function

だから、私は(提案されたように)これを使用してthis.eraseを呼び出すしようとすると:これらのどちらも働いている

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

this.myInput.changed(function(){ myself.erase(); }); 
は、私はすべての異なる可能性を試してみました Uncaught TypeError: undefined is not a function 同じエラーを取得します。

this.eraseはオブジェクトの異なるインスタンスと複数のDOM要素から多くの時間を呼び出す必要があるため、=>関数を使用することはできません。

答えて

0

あなたはそれを参照できるように変数にthisを保存する必要があります。

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(); 
} 

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

別の(あまりエレガント)ソリューションは、このことだろう

関連する問題