I have trouble calling a method from one class in other classes. The only way I made it work was to pass in the class (that has the method) and then use new keyword. I dont think it can be right/good to always using new keyword in every class I want to use the method (when having multiple classes containing mult. methods). How can I do that? Also, inheriting from other classes isnt a good way eeither as I would inherit all of its properties and it wouldnt really fit as i dont have parent/child relationships. Could anyone help? Thanks!
html:
<input id="title"/>
<input id="description"/>
<button id="add">Add</button>
class EventHandler{
constructor(Todo){}
init() {
const button = document.querySelector("#add");
const todo = new Todo();
button.onclick = todo.addItem;
}
}
class Todo {
constructor(title, description, UIManager){
this.title = title;
this.description = description;
}
addItem() {
const uiManager = new UIManager;
const todoItem = uiManager.getData();
}
}
class TodoManager {
constructor(){}
}
class UIManager {
constructor(){}
getData() {
const title = document.querySelector("#title").value;
const description = document.querySelector("#description").value;
const todoItem = new Todo(title, description);
return todoItem;
}
}
(() => {
const todoManager = new TodoManager();
const uiManager = new UIManager();
const eventHandler = new EventHandler();
let todoItem = uiManager.getData();
eventHandler.init()
})()
ps.: I was thinking somehow to do it insight my init function, but there I havent created my todoitem yet and I keep getting errors about undefined classes whatever I tried here.
答案 0 :(得分:1)
Why is UIManager a class? It doesn't create anything useful. If you want a function library, just use a plain object:
const UIManager = {
getData: () => {
const title = document.querySelector("#title").value;
const description = document.querySelector("#description").value;
const todoItem = new Todo(title, description);
return todoItem;
}
}
Same thing with EventHandler.
If said classes did return a useful object you wanted to work with, but you still wanted to access general class utility methods not related to those objects, you could use the static
keyword:
class Something {
constructor() {
this.something = 'somethingelse';
}
static getInfo() {
return 'some info';
}
}
console.log(Something.getInfo());
答案 1 :(得分:0)
If you have some reason to make UIManager
a class, make the method static
:
class UIManager {
constructor(){}
static getData() {
const title = document.querySelector("#title").value;
const description = document.querySelector("#description").value;
const todoItem = new Todo(title, description);
return todoItem;
}
}
let todoItem = UIManager.getData();