0
In dem Ausschnitt unten versuche ich, eine Funktion auf dem Controller des Elternteils aufzurufen.Wie ruft man eine Funktion auf dem übergeordneten Controller auf?
Welche Optionen bietet Mithril?
class Parent {
view(vnode){
return m(Child, {onaction: this.onAction});
}
onAction =() => { //TO BE CALLED BY CHILD
console.log('on action');
}
};
class Child {
view(vnode){
return m(Button, {onclick: this.onClick})
}
onClick =() => {
// NEEDS TO CALL PARENT'S ONACTION FUNCTION FROM HERE
console.log('click');
}
};
class Button {
view(vnode){
return m('button', vnode.attrs, 'button')
}
}
m.render(document.body, m(Parent));
<script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/1.1.1/mithril.min.js"></script>
Eine Lösung wäre vnode
in Kinder Controller zu speichern und dann this.vnode.attrs.onaction()
von onClick
Handler aufrufen, aber wäre es nicht ein Anti-Muster sein?
class Parent {
view(vnode){
return m(Child, {onaction: this.onAction});
}
onAction =() => {
console.log('on action');
}
};
class Child {
view = (vnode) => { //Is it ok to bind it?
this.vnode = vnode;
return m(Button, {onclick: this.onClick})
}
onClick =() => {
console.log('click');
this.vnode.attrs.onaction();
}
};
Sie haben eine Funktion mit Attributen in Ihrem Kind zu verknüpfen Komponente, die Sie übergeben. Und rufen Sie die Funktion von attrs aus von Ihrer Kindkomponente auf. – Godje