Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write an external function to call a method invocation while compiling Gleam code to JavaScript?

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.

like image 461
Harshal Patil Avatar asked Sep 16 '25 03:09

Harshal Patil


1 Answers

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)
}
like image 136
lpil Avatar answered Sep 17 '25 18:09

lpil