Elm有调试功能可以将对象打印到控制台吗?

时间:2016-08-03 01:33:35

标签: elm

我希望能够检查运行时javascript对象。我可以将对象打印到控制台而不是字符串吗?

3 个答案:

答案 0 :(得分:12)

您可以使用Debug.log,例如:

import Html exposing (text)

f x = x * x

main =
  let
    dummy = Debug.log "dump tuple" (33, 55, f)
  in text "Hello, World!"

答案 1 :(得分:5)

在使用编码器时,我需要更丰富的日志记录,因此最终为它编写了port。这是working example on Ellie,下面是代码:

Main.elm

port module Main exposing (main)

import Browser
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)
import Json.Encode as E exposing (Value, int, object, string)


type alias Model =
    { count : Int
    , name : String
    }


initialModel : Model
initialModel =
    { count = 0
    , name = "Foo"
    }


encodeModel : Model -> Value
encodeModel model =
    object
        [ ( "count", int model.count )
        , ( "name", string model.name )
        ]


port jsonConsole : Value -> Cmd msg


type Msg
    = ConsoleLogJson


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        ConsoleLogJson ->
            let
                json =
                    encodeModel model
            in
            ( model, jsonConsole json )


view : Model -> Html Msg
view model =
    div [] [ button [ onClick ConsoleLogJson ] [ text "Log to console" ] ]


subscriptions : Model -> Sub Msg
subscriptions _ =
  Sub.batch []


init : () -> ( Model, Cmd msg )
init flags =
    ( initialModel, Cmd.none )


main : Program () Model Msg
main =
    Browser.element
        { init = init
        , subscriptions = subscriptions
        , view = view
        , update = update
        }

index.html

<html>
<head>
  <style>
    /* you can style your program here */
  </style>
</head>
<body>
  <main></main>
  <script>
    var app = Elm.Main.init({ node: document.querySelector('main') })
    app.ports.jsonConsole.subscribe(function(json) {
      console.log(json)
    })
  </script>
</body>
</html>

我确定可以做出一些改进,我很想听听他们的意见!

答案 2 :(得分:4)

不幸的是,没有。在使用Debug.log时,所有对象在转发到控制台之前都会转换为字符串。

但是,您可以创建一个使用Native层输出实际对象的函数,但是,这是一个未记录的API,建议仅将其用作最后的手段。