显示加载占位符'在Elm中渲染DOM元素

时间:2016-11-29 21:30:54

标签: elm

当Elm要做很多DOM操作时,在结果显示之前会有一些延迟。我试图弄清楚如何显示一个占位符div,表示"正在加载......"而榆树正在做它的事情。

为了证明延迟,我修改了Elm examples中的一个,以便在点击按钮时呈现越来越多的文本元素:

import Html exposing (beginnerProgram, div, button, text)
import Html.Events exposing (onClick)

main =
  beginnerProgram { model = 0, view = view, update = update }


view model =
  div []
    [ button [ onClick Decrement ] [ text "-" ]
    , div [] [ text (toString model) ]
    , button [ onClick Increment ] [ text "+" ]
    , div [] (List.repeat (2 ^ model) (text ". ")) -- this is my addition
    ]

type Msg = Increment | Decrement

update msg model =
  case msg of
    Increment ->
      model + 1

    Decrement ->
      model - 1

运行示例时,点击' +'按钮将显示'。' 2.当数字足够高(我的机器上大约16)时,在点击之前有一个多秒的延迟。'字符显示。

显示“加载...”的好方法是什么?'在渲染'之前的元素(在' div'中)。元素?

1 个答案:

答案 0 :(得分:4)

您需要使用常规Html.program并从Cmd / Increment更新处理程序返回Decrement,这些处理程序将暂停以让DOM呈现&#34 ;加载"然后重新输入update

import Html exposing (program, div, button, text)
import Html.Events exposing (onClick)
import Process
import Task

main =
  program { init = (Model 0 False, Cmd.none), view = view, update = update, subscriptions = \_ -> Sub.none }

type alias Model =
  { count: Int
  , loading: Bool
  }

view model =
  let
    dotsDisplay =
      if model.loading then
        div [] [text "Loading..."]
      else
        div [] (List.repeat (2 ^ model.count) (text ". "))
  in
    div []
      [ button [ onClick Decrement ] [ text "-" ]
      , div [] [ text (toString model.count) ]
      , button [ onClick Increment ] [ text "+" ]
      , dotsDisplay
      ]

type Msg = Increment | Decrement | FinishLoading

finishLoadingCmd =
  Task.map2 (\_ b -> b) (Process.sleep 10) (Task.succeed FinishLoading)
  |> Task.perform identity

update msg model =
  case msg of
    Increment ->
      {model | count = model.count + 1, loading = True} ! [finishLoadingCmd]

    Decrement ->
      {model | count = model.count - 1, loading = True} ! [finishLoadingCmd]

    FinishLoading ->
      {model | loading = False} ! []

在渲染所有这些节点时,它仍然会锁定浏览器,所以你可能仍然希望寻找一种不渲染100k + DOM元素的方法......