I am trying to write the Gleam JavaScript binding for basic DOM manipulation. I want to achieve the following JavaScript functionality with Gleam:
const div = document.createElement('div');
div.classList.add('className');
I am writing the following external definition:
pub external type Document
pub external type HTMLElement
pub external fn create_elm(String) -> HTMLElement =
"" "document.createElement"
// How can I write the following external definition?
pub external fn add_class(HTMLElement, String) -> Nil =
"" "$0.classList.add"
So, for add_class
function, I want Gleam to compile to JavaScript such that first argument HTMLElement
is used as an object and the second argument String
is passed to the some method of the HTMLElement
. How can I achieve this?
I could not find any documentation for this on the Gleam website. I thought something like the way Fable allows writing external binding would be possible. However, that doesn't work.
Gleam doesn't have any functionality for working with OOP JavaScript so in this case I would use some JavaScript glue code.
// in src/app.gleam
pub type Document
pub type HTMLElement
@external(javascript, "./app_ffi.mjs", "createElement")
pub fn create_elm(kind: String) -> HTMLElement
@external(javascript, "./app_ffi.mjs", "addClass")
pub fn add_class(el: HTMLElement, class: String) -> Nil
// in src/app_ffi.mjs
export function createElement(kind) {
return document.createElement(kind)
}
export function addClass(element, string) {
element.classList.add(string)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With