summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorBrian Cully <bjc@spork.org>2025-08-07 12:05:51 -0400
committerBrian Cully <bjc@spork.org>2025-08-07 12:05:51 -0400
commit58f6fbe0afb828571463a22737603a037b059909 (patch)
tree5a2027883c4970f1876164b9e45d0691988ccf66
parentb2e411de770a437dbdf31408b877e2952759e57a (diff)
downloadaddem-rust-wasm-58f6fbe0afb828571463a22737603a037b059909.tar.gz
addem-rust-wasm-58f6fbe0afb828571463a22737603a037b059909.zip
add imports from javascript
‘alert’ and ‘console.debug’
-rw-r--r--index.html2
-rw-r--r--main.mjs6
-rw-r--r--src/lib.rs23
3 files changed, 22 insertions, 9 deletions
diff --git a/index.html b/index.html
index 1aad79c..cc13062 100644
--- a/index.html
+++ b/index.html
@@ -13,6 +13,8 @@
result: <span id='result'></span>
</p>
+ <button onclick='testalert()'>alert</button>
+
<script src='./main.mjs' type='module'></script>
</body>
</html>
diff --git a/main.mjs b/main.mjs
index 086b876..d8fe63a 100644
--- a/main.mjs
+++ b/main.mjs
@@ -4,6 +4,7 @@ async function run() {
console.debug('run');
const foo = await init();
console.debug('init done', foo);
+
window.calculate = _ => {
console.debug('calc');
const inp1 = document.getElementById('number-input1').value;
@@ -11,6 +12,11 @@ async function run() {
const res = foo.add(parseInt(inp1), parseInt(inp2));
document.getElementById('result').textContent = res;
}
+
+ window.testalert = _ => {
+ console.debug('testalert');
+ foo.test_alert('from js');
+ }
}
document.addEventListener('DOMContentLoaded', run);
diff --git a/src/lib.rs b/src/lib.rs
index 7db4248..7129898 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,17 +1,22 @@
use wasm_bindgen::prelude::wasm_bindgen;
#[wasm_bindgen]
+extern {
+ fn alert(s: &str);
+
+ // set the namespace so we can use ‘console.debug’
+ #[wasm_bindgen(js_namespace = console)]
+ fn debug(s: &str);
+}
+
+#[wasm_bindgen]
pub fn add(left: u32, right: u32) -> u32 {
+ debug(&format!("adding the numbers {} and {}",
+ left, right));
left + right
}
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn it_works() {
- let result = add(2, 2);
- assert_eq!(result, 4);
- }
+#[wasm_bindgen]
+pub fn test_alert(s: &str) {
+ alert(s)
}