2017-10-08 12 views
0

私のJSクラスの多くは、私のページを白い背景でカバーする基本モーダルを呼び出します。最近私はいくつかのコードを改訂しようとしましたが、私はそのモーダルを独自のクラスに入れました。私が遭遇した問題は、モーダル変数が登録されていない兄弟クラスからモーダルクラスを呼び出すときです。私はいくつかの人と話をしてきました。彼らは多態性を調べることを勧めましたが、読んだところでは親子関係(拡張の使用)に関係しているようです。私はバニラJSが兄弟と兄弟と授業をやりとりするための簡単な方法があれば興味がありましたか?私はこれがたくさん触れられているが、私は周りを見ていたし、私が必要なものを見つけることができない場合はお詫び申し上げます。JS兄弟クラス間でのイベントの受け渡し

class Modal { 
    constructor(modal){ 
    this.modal = modal; 
    this.closeButton = modal.querySelector('.modal-close-button'); 
    } 

    activate() { 
    this.modal.setAttribute('data-state', 'active'); 
    document.body.setAttribute('data-state', 'inactive'); 
    } 

    deactivate() { 
    this.modal.setAttribute('data-state', 'inactive'); 
    document.body.setAttribute('data-state', 'active'); 
    } 
} 

class Form { 
    constructor(button, modal) { 
    this.button = button; 
    this.formId = button.getAttribute('data-form'); 
    this.modal = modal; 
    this.setEvents(); 
    } 

    setEvents() { 
    this.button.addEventListener('click', this.modal.activate); 
    } 
} 
+1

あなたの問題はthis'はである何 'であるFormクラスを変更することができ、またconstructor

class Modal { constructor(modal){ this.modal = modal; this.closeButton = modal.querySelector('.modal-close-button'); // add these two lines this.activate = this.activate.bind(this); this.deactivate = this.deactivate.bind(this); } activate() { this.modal.setAttribute('data-state', 'active'); document.body.setAttribute('data-state', 'inactive'); } deactivate() { this.modal.setAttribute('data-state', 'inactive'); document.body.setAttribute('data-state', 'active'); } } 

thisthis.activateをバインドすることですイベントハンドラ –

+0

あなたは 'Form#setEvents'とそれに応じて' Modal'のハンドラを修正する必要があります –

+0

助けてくれてありがとうJaromanda X、I fこれは私が通常このクラスを使ってこの問題を処理するときにthis.function.bind(this)を使用する場合に当てはまりましたが、(私)がModalとの関係に設定する方法がわかりません。あなたは精巧にお考えですか? – Jleibham

答えて

1

最も簡単な修正は、あなたが

class Form { 
    constructor(button, modal) { 
    this.button = button; 
    this.formId = button.getAttribute('data-form'); 
    this.modal = modal; 
    this.setEvents(); 
    } 

    setEvents() { 
    this.button.addEventListener('click', e => this.modal.activate(e)); 
    } 
} 
+0

Ah!ありがとう、これはトリックをするようだ。ですから、基本的に別のクラスのクラスメソッドを呼び出す場合は、そのメソッドを.bind(this)でコンストラクタに追加する必要があります。 – Jleibham

+0

いいえ、イベントハンドラと関係があります –

+0

@ JaromandaXさんの回答が気に入っていますが、次のオプションもあります: 'this.button.addEventListener( 'click'、()=> this.modal.activate());' –

関連する問題