2017-04-05 33 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

非常感謝! :)我怎麼能通過輸入值作爲參數? 'document.getElementById('edtNoteTitle')。value'例如'' ? – peterHasemann

+0

youre歡迎,關於第二個問題 - 幾乎應該是'onclick =「NoteController.CreateNote(」+ document.getElementById('edtNoteTitle')。value +「)」' – lustoykov

+0

謝謝:)幫助 – peterHasemann