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