Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to use JavaScript attribute by default?

Tags:

f#

websharper

I just want somehow to say "I want all methods in this project use [JavaScript]" Manually annotation every method is annoying

like image 670
ais Avatar asked Apr 09 '13 09:04

ais


3 Answers

F# 3 lets you mark a module with the ReflectedDefinition attribute (aka [JavaScript] in WebSharper) which marks all the methods underneath.

See More About F# 3.0 Language Features:

(Speaking of uncommon attributes, in F# 3.0, the [< ReflectedDefinition >] attribute can now be placed on modules and type definitions, as a shorthand way to apply it to each individual member of the module/type.)

like image 73
Phillip Trelford Avatar answered Oct 22 '22 14:10

Phillip Trelford


I think Phil's answer is the way to go - when you can mark an entire module or type, it does not add too much noise and it also allows you to distinguish between server-side and client-side code in WebSharper.

Just for the record, the F# compiler is open-source and so someone (who finds this issue important) could easily create branch that would add an additional command line attribute to override the setting. I think this is just a matter of adding the parameter and then setting the default value of the reflect flag in check.fs (here is the source on GitHub).

At the moment, the main F# repository does not accept contributions that add new features (see the discussion here), but it is certainly a good way to send a feature request to the F# team :-)

like image 26
Tomas Petricek Avatar answered Oct 22 '22 14:10

Tomas Petricek


If you annotate all your code with the JavaScript attribute, the WebSharper compiler will try to translate everything to JavaScript. A rule of thumb in WebSharper development is to separate server-side and client-side code, so you can simply annotate the module/class containing client-side code instead of every function/member if you're targeting .NET 4.5.

namespace Website

open IntelliFactory.WebSharper

module HelloWorld =

    module private Server =

        [<Rpc>]
        let main() = async { return "World" }

    [<JavaScript>] // or [<ReflectedDefinition>]
    module Client =

        open IntelliFactory.WebSharper.Html

        let sayHello() =
            async {
                let! world = Server.main()
                JavaScript.Alert <| "Hello " + world
            }

        let btn =
            Button [Text "Click Me"]
            |>! OnClick (fun _ _ ->
                async {
                    do! sayHello()
                } |> Async.Start)

        let main() = Div [btn]

    type Control() =

        inherit Web.Control()

        [<JavaScript>]
        override __.Body = Client.main() :> _
like image 31
Taha Avatar answered Oct 22 '22 13:10

Taha