2017-12-08 6 views
1

私は5つのオブジェクト(つまりクラスのインスタンス)を持っており、関数 "squash()"を実行する "im"プロパティにイベントリスナーを設定する必要があります。クラスのすべてのインスタンスのプロパティにイベントリスナーを作成するにはどうすればよいですか?

this.im.click(squash())をクラス内で使用しようとしましたが、動作しませんでした。イベントリスナーを作成するにはどうすればよいですか?

let divs = $(".flies"); 
divs.each(function(i){ 
    let img = $("<img/>"); 
    img.attr({ 
    "id": i, 
    "src": "http://clipart-library.com/images/8iznoLG8T.png"}); 
    $(this).append(img) 
}); 

class Fly { 
    constructor(div, im, alive){ 
    this.div = div; 
    this.im = im; 
    this.alive = true; 
    } 
    squash(){ 
    this.alive= false; 
    this.element.css("visibility", "hidden"); 
    } 
    } 

let fly1 = new Fly($('#fly1'), $('#0'), true); 
let fly2 = new Fly($('#fly2'), $('#1'), true); 
let fly3 = new Fly($('#fly3'), $('#2'), true); 
let fly4 = new Fly($('#fly4'), $('#3'), true); 
let fly5 = new Fly($('#fly5'), $('#4'), true); 
+1

'this.im.click(スカッシュ)'(なしブラケット)あなたが関数を呼び出すthis.im. 'をクリックハンドラを追加しませんクリック(squash()) ' – Liam

+0

@Liamは' this'のコンテキストを変更します – charlietfl

+0

これは別の問題です。 'squash'がクリックハンドラであれば、' this'はOPがそれをとにかく考えるものではありません。 – Liam

答えて

0

使用im.click(this.squash.bind(this));

class Fly { 
 
    constructor(div, im, alive){ 
 
    this.div = div; 
 
    this.im = im; 
 
    this.alive = true; 
 
    this.init() 
 
    } 
 

 
    init(){ 
 
    this.im.click(this.squash.bind(this)); 
 
    } 
 
    
 
    squash(){ 
 
    this.alive= false; 
 
    // wasn't sure what `element` is supposed to be, used `div` instead 
 
    this.div.css("visibility", "hidden"); 
 
    } 
 
    } 
 

 
let fly1 = new Fly($('#fly1'), $('#0'), true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="0">Click to hide content</button> 
 

 
<div id="fly1">Content 1</div>

関連する問題