我想做类似的事情:
open Webapi.Dom;
let addListener = (element) =>
EventTarget.addEventListener("click", onSubscribeClick, EventTarget.asEventTarget(element));
let addOrRemoveListeners = (handler, ()) => {
let elements = Document.querySelectorAll({j|[$subscriptionIdAttr]|j}, document);
Js.Array.forEach(handler, NodeListRe.toArray(elements) |> Js.Array.map(Element.ofNode))
};
let addListeners = addOrRemoveListeners(addListener);
let removeListeners = addOrRemoveListeners(removeListener);
但我在addOrRemoveListeners(addListener);
中收到错误:
This is:
(Dom.eventTarget) => unit
But somewhere wanted:
(Dom.node) => unit
我应该如何从Dom.eventTarget
转换为Dom.node
?
编辑:我最终得到了这个:
let addListener = Element.addEventListener("click", onSubscribeClick);
let removeListener = Element.removeEventListener("click", onSubscribeClick);
let addOrRemoveListeners = (handler, ()) => {
let elements = Document.querySelectorAll({j|[$(subscriptionIdAttr)]|j}, document);
let () =
elements
|> NodeListRe.toArray
|> Array.map(Element.ofNode)
|> Array.to_list
|> List.filter(Js.Option.isSome)
|> List.map(Js.Option.getExn)
|> List.iter(handler);
()
};
let addListeners = addOrRemoveListeners(addListener);
let removeListeners = addOrRemoveListeners(removeListener);
答案 0 :(得分:1)
简短回答:
external eventTargetToNode : Dom.eventTarget => Dom.node = "%identity";
eventTarget
几乎可以是任何东西,遗憾的是没有好办法搞清楚它是什么。在JavaScript中,它只是由用户根据上下文推断出来(有可能在类型参数中携带该上下文,但在将来的某个地方也是如此)。
所以目前你必须做一个不安全的演员才能得到你需要的东西。
(顺便说一句,您可以使用Element.addEventListener
来避免从element
转换为eventTarget
)