Reference · Browser

js_new

signature
js_new(str, any...) -> any

What it does

Makes an object of a class the page's scripts define, by its dotted name, with the arguments given to its constructor: js_new("Chart", el, config) is new Chart(el, config). The object's methods and properties are then fields: chart.update(), chart.destroy(). It runs in the browser, from a component; while the server renders the component it gives null. A name the page does not have is an error value.

A library named on a client line is called the same way, as JavaScript reads it: client "https://.../chart.umd.min.js" use Chart, then Chart.new(el, config) is js_new("Chart", el, config), and the page loads the script itself (see JavaScript libraries).

Examples

in a program
component Sales(points: list) {    state chart = null    <canvas @mount={(el) => {        chart = js_new("Chart", el, { type: "line", data: points })        () => chart.destroy()                   // when the canvas leaves the page    }}></canvas>}route GET / = <html><head><script src="/assets/chart.js"></script></head>                    <body><Sales points={load_points()}/></body></html>

Edge cases

print(js_new("Chart", 1, 2))print(js_new("Map") ?? "no page")
output
nullno page

Errors

A first argument that is not a string is a runtime error on the server, with the same message as js.

this one fails
print(js_new(42))
output
line 1: `js` takes the name of what it calls first: js("Chart", ...)

Chaining

The object is what gets chained, through its methods:

in a program
let map = js_new("L.Map", el, { center: [51.5, -0.1], zoom: 12 })map.on("moveend", () => { center = map.getCenter() })

See also

js, ask, notify

Thread
6Useful? Like it, or add to its thread below.

Thread 0 posts

On js_new(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo