Search code examples
f#websharper

Accessing JavaScript's this from WebSharper


I feel a bit dumbfounded at how I have yet to find how to access the JavaScripts this keyword from WebSharper client code.

I tried something like this:

[<Inline "$this">]
let this() = X<obj>

But this spits out $this in the generated js code which doesn't seem to refer to the correct scope object.

It feels that I shouldn't have to write any extra code though and that it should be part of the API.

Thanks


Solution

  • So the general idea would be that when using WebSharper you will seldom need to navigate the DOM as you would with conventional site.

    Having a wealth of combinators to create markup at the client side combined with the ease of RPC calls favors the pattern of creating all content on the client using javascript.

    I.E. you tend to return data and in turn generate the markup interactively, only resorting to server-side markup as the need arise to create bookmark locations and useful links.

    Therefore, you can generally keep reference to DOM elements when you create them simply by binding them to a variable for later use.

    In my personal use-case, I wanted to access this, but later realized that this was a reference to the Kendo grid which I held a reference to when I created it. I therefore didn't need to use this.

    Aside from that, there are the not-so obvious technical limitations imposed by an F#-to-javascript compiler of that nature. I feel uncomfortable detailing them here as I do not fully understand them, but feel free to see Anton's answer through the fpish.net link above.