How can I export console log win Elm?

Viewed 484

It is difficult to export console.log with Elm.

I want to output the console log by pushing button like below and with console log in function. How shold I do?

sampleView : Html Message
sampleView =
    Html.div (class "sample-card" :: Styles.sampleCard)
        [ Html.div
            (class "sample-card-list" :: Styles.sampleCardList)
            [
                Html.button
                    (class "sample-card-button" :: Styles.sampleCardListButton)
                    [
                        Html.text "サンプルボタン"
                    ]
            ]
        ]

If I use Javascript, I want to do like below.

<button class="sample-card-button" onclick="btnClick();">サンプルボタン</button>

/* JavaScript 側 */
function btnClick() {
  console.log("クリックされました");
});
1 Answers

If it's just for debugging, you can use Debug.log, but you can't use the Debug module in production code (running the compiler with --optimize will fail to compile if you have Debug usages). Using it can look like this:

sampleView : Html Message
sampleView =
    Html.div (class "sample-card" :: Styles.sampleCard)
        [ Html.div
            (class "sample-card-list" :: Styles.sampleCardList)
            [
                Html.button
                    ([class "sample-card-button", onClick CardButtonClicked] ++ Styles.sampleCardListButton)
                    [
                        Html.text "サンプルボタン"
                    ]
            ]
        ]

update : Message -> Model -> ( Model, Cmd Message )
update msg model =
    case msg of
        CardButtonClicked ->
            let
                _ = Debug.log "クリックされました" msg
            in
            ( model, Cmd.none )

If you want to write to the console in a production app, you'll need to use a port. To create a port, you'll need to update the module it's in to be declare a port module (just add port to the beginning of of the module declaration on the first line of the file).

port module Main exposing (..)

port consoleLog : String -> Cmd msg

update : Message -> Model -> ( Model, Cmd Message )
update msg model =
    case msg of
        CardButtonClicked ->
            ( model, consoleLog "クリックされました" )

Then you'll need to wire up some JavaScript to handle that port message:

var app = Elm.Main.init({ node: document.querySelector('main') })
app.ports.consoleLog.subscribe(function (msg) {
    console.log(msg);
});

Here's an example app using a port to call console.log.

Related