2017-04-05 19 views
2

JavaScriptでクラスを取得しました。このクラスでは、テキストフィールドの入力をチェックするメソッドがあります。 htmlドキュメントの本体がロードされているとき、このメソッドを初めて呼び出す必要があります。その後、私は "onchange()"イベントを使いたい。JavaScriptクラスの呼び出しメソッド

//############## 
//# Javascript # 
//############## 

class NoteController{ 
    constructor() { 
    this.store = new NoteStore(); // instance of a dataStore 
    } 

    HandleInputFields(){ // Enable/Disable a button by validation 
    var input = document.getElementById('edtNoteTitle').value; // Get the input text from the field 
    var inputIsValid = true; 

    if(input.length < 1) // text is empty 
     inputIsValid = false; 
    else if (this.store.notes.some(n => n.title === input)) // check for duplicates in the store 
     inputIsValid = false; 

    document.getElementById('btnCreateNote').disabled = !inputIsValid; // disable the button or keep it enabled 
    } 
} 

//######## 
//# HTML # 
//######## 

<body onload="HandleInputFields()"> // Disable the button when loading the Document 

<input type="text" id="edtNoteTitle" onchange="HandleInputFields()"> // Validate the Input field 

</body> 

私は自分のドキュメントを開くとき、「HandleInputFields()」は定義されていないと言います。どのようにしてこのメ​​ソッドを正しく呼び出すことができますか?

答えて

2

メソッドをstaticとして定義し、class 'スコープでアクセスする必要があります。

のでclass NoteController { ...

変更にHandleInputFields() { static HandleInputFields() {に、その後は

<body onload="NoteController.HandleInputFields()"> 

説明を経由してアクセス:現在、あなたはwindow.HandleInputFields()にフォールバックコンテキストなしでメソッドにアクセスしようとしています。しかし、あなたの目的はNoteControllerのコンテキストを経由してアクセスすることです。したがって、NoteController.HandleInputFields()というコールがあります。ただし、インスタンスではなくクラスで直接呼び出しを行うには、staticと定義する必要があります。

+0

ありがとうございました! :)そして、私はどのように入力値をパラメータとして渡すことができますか? 'button type = "button" id = "btnCreateNote" onclick = "NoteController.CreateNote(document.getElementById(' edtNoteTitle ')。value)"> Create 'document.getElementById(' edtNoteTitle ')。 ? – peterHasemann

+0

youre歓迎、約2番目の質問 - ほぼ、 'onclick =" NoteController.CreateNote( "+ document.getElementById( 'edtNoteTitle')。value +") "' " – lustoykov

+0

ありがとうございました:) – peterHasemann

関連する問題