-
Notifications
You must be signed in to change notification settings - Fork 0
I Do Not Get Any Values Defined in my View in Callbacks with 'this'
You are from the C# or Java world and just found that this does not point to anything in your Typescript class, especially when callback from m("button", { onclick: processClick }, "Just do it") is called. Any class property values that I defined isn't there through this.
That is not a problem with Mithril. This is a very common JavaScript specific issue.
If you are from C, C#, Java world, you will likely run into this issue. This use of this is JavaScript specific and the meaning of "this" is quite a bit different and even changes depending how a function is called, almost looking like it is completely inexplicable.
By seasoned JavaScript developers, "this" is considered a "novice" error. Do not feel bad because I make this mistake all the time myself as I need to switch between all these languages.
Rather than giving you a lengthy discussion on the closure and the meaning of "this", here is a quick solution.
-
Include much of what you need in the object that is assigned to your vnode.state, then bind that to the callback. If you do so, then your processClick() will have the this value which points to vnode.state and you can carry on.
m("button", { onclick: processClick.bind(vnode.state) }, "Just do it");
Or,
-
Capture your view object's this as self then pass that to the callback like this;
private myData = "my data";
view(vnode: Mithril.Vnode) {
const self = this; return m("button", { onclick: processClick.bind(self) }, "Just do it");
}
In this case myData in your component is availalbe as this.myData in your callback.
This open source product is provided under the terms of the MIT License.