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

두 번째 질문에 오신 것을 환영합니다. 거의 'onclick = "NoteController.CreateNote ("+ document.getElementById ('edtNoteTitle '). value + ")" – lustoykov

+0

감사합니다. – peterHasemann