Search code examples
f#websharper

Capturing keyboard input Websharper


I'd like to get the keyboard input of a user in Websharper for an entire page (or whatever gets me closest), and I can't see any nice way of doing this.

I've attempted something along the lines of

JQuery.Of("document").Keyup(fun _ _ -> Window.Self.Alert("boo"))

But I keep running into a lot of NotImplementedExceptions. Are these really not implemented? Or am I hitting some weird edge case because I'm going against the grain?

Update:

I've got version 2.4.85.235 installed from nuget, if that means anything to anyone. I'm also using VS 2012.

I've also tested with a fresh sitelets templated site from VS 2010, and I see the same thing. I've installed the latest package from the WebSharper site.


Solution

  • Make sure that you're not calling client-side methods that are not implemented on the server. If that's the case separate client and server code, display the involved elements and invoke the JavaScript through the Web Control mechanism and use "html", "body" or Dom.Document.Current as a selector. Below is a sample for displaying an alert every time the enter key is pressed:

    module Client =
    
        open IntelliFactory.WebSharper
        open IntelliFactory.WebSharper.Html
        open IntelliFactory.WebSharper.JQuery
    
        [<JavaScriptAttribute>]
        let paragraph () =
            P [Text "Press the Enter key to display an alert box."]
            |>! OnAfterRender (fun x ->
                JQuery.Of("html").Keydown(fun _ event ->
                    match event.Which with
                        | 13 -> JavaScript.Alert "Enter key was pressed."
                        | _  -> ()).Ignore)
    
        type ParagraphViewer () =
            inherit Web.Control()
    
            [<JavaScript>]
            override this.Body = paragraph () :> _