我正在使用 elm 0.17.1 并尝试与 select2 javascript 库(版本 4.0.3)互操作,这是我的 Main.elm :
port module Main exposing (..)
import Html exposing (Html,select,option,div,text,br)
import Html.App as App
import Html.Attributes exposing (id,value,width)
-- MODEL
type alias Model =
{
country : String
}
-- UPDATE
type Msg =
Select String
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
Select str -> (Model str,Cmd.none)
-- VIEW
view : Model -> Html Msg
view model =
div[]
[
select [id "myselect"]
[
option [value "US"] [text "United States"],
option [value "UK"] [text "United Kingdom"]
],
text model.country
]
-- SUBSCRIPTIONS
port selection : (String -> msg) -> Sub msg
subscriptions : Model -> Sub Msg
subscriptions _=
selection Select
port issueselect2 : String -> Cmd msg
-- INIT
init : (Model, Cmd Msg)
init =
({country=""},issueselect2 "myselect")
main : Program Never
main = App.program {init=init,view=view,update=update,subscriptions=subscriptions}
和 javascript 方面:
$(document).ready(function()
{
var app=Elm.Main.fullscreen();
app.ports.issueselect2.subscribe(function(id)
{
$('#'+id).select2().on('change',function(e)
{
app.ports.selection.send(e.target.value);
});
})
})
现在,当我选择一个国家/地区时,我的 Chromium 控制台中会出现 Uncaught 类型错误,提示
domNode.replaceData
不是一个函数(它实际上是未定义的)。问题是 select2 向 DOM 添加了一个 span 而 Elm 不知道它,检查
domNode
揭示 Elm 试图更新 span
什么时候应该更新文本。我想我需要效果,但我不知道如何在我的特定用例中使用它们。
如何解决我的问题?
对于我使用 jquery 3 的记录,我将我的 elm 程序编译到 main.js 中,然后按以下顺序加载 js 文件:jquery.min.js、select2.min.js、main.js 然后是上面的 js 代码。
我无法用 elm-reactor 调试它,因为它似乎只适用于 elm 代码而不是 js 代码。
最佳答案
为了解决这个问题,我做了 this example演示将任何第三方 JavaScript 技术集成到您的 Elm 应用程序的所有核心思想。
以下是规则:
查看
$(document).ready()
, 如果 Elm 应用程序控制初始化逻辑
示例中的兴趣点:
该 View 为所有 jQuery 魔法提供了一个容器:
view : Model -> Html Msg
view model =
div []
[ text (toString model)
, div [ id "select2-container" ] [] -- The container, where select2 will live
]
非常欢迎任何反馈,如果您能告诉我缺少什么,我愿意改进这个答案。
关于javascript - 如何告诉 elm 有关外部 DOM 更改的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40544433/