42 lines
1.4 KiB
EmacsLisp
42 lines
1.4 KiB
EmacsLisp
// browser-counter.el — canonical browser DOM bridge example
|
|
//
|
|
// Compile with: elc --target=js examples/browser-counter.el > counter.js
|
|
//
|
|
// Then include in an HTML page that has a <span id="count-display"> element.
|
|
// The page can call window.increment() from any onclick handler, e.g.:
|
|
// <button onclick="increment()">+1</button>
|
|
//
|
|
// On load the display is initialised to "0". Each call to increment()
|
|
// adds 1 and updates the display text.
|
|
//
|
|
// Demonstrates:
|
|
// - dom_get_element to locate a DOM node by id
|
|
// - dom_set_text to update visible text content
|
|
// - dom_is_null to guard against missing elements
|
|
// - window_set to expose an El function for inline event handlers
|
|
// - state_set/get for in-memory counter state (survives calls, resets
|
|
// on page reload — same semantics as the C state_* API)
|
|
|
|
fn init() -> Void {
|
|
state_set("counter", 0)
|
|
let display = dom_get_element("count-display")
|
|
if !dom_is_null(display) {
|
|
dom_set_text(display, "0")
|
|
}
|
|
}
|
|
|
|
fn increment() -> Void {
|
|
let current = str_to_int(state_get("counter"))
|
|
let next = current + 1
|
|
state_set("counter", next)
|
|
let display = dom_get_element("count-display")
|
|
if !dom_is_null(display) {
|
|
dom_set_text(display, int_to_str(next))
|
|
}
|
|
}
|
|
|
|
fn main() -> Void {
|
|
init()
|
|
window_set("increment", increment)
|
|
}
|