0Pricing
WebAssembly (WASM) for High Performance Apps · 강의

사용자 지정 JavaScript 콜백

WebAssembly 모듈 내부에서 호출할 수 있는 사용자 지정 JavaScript 함수를 설계하고 구현합니다.

사용자 지정 JavaScript 콜백은(는) CoddyKit의 무료 WebAssembly (WASM) for High Performance Apps 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebAssembly (WASM) for High Performance Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebAssembly (WASM) for High Performance Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Calling JavaScript from WASM

Sometimes, your WebAssembly (WASM) module needs to communicate back to the JavaScript environment it's running in. This is where custom JavaScript callbacks become essential!

They allow your WASM code to trigger actions or pass data back to your web page, making your applications more interactive.

Why WASM Needs Callbacks

Imagine your WASM module performs complex calculations or processes data. Once it's done, it often needs to:

  • Update the UI: Notify JavaScript to refresh a chart or display a result.
  • Access Browser APIs: Request JavaScript to use APIs WASM can't directly access, like `localStorage` or `fetch`.
  • Log Information: Send debugging messages or status updates to the browser console.
  • Handle Events: Respond to user interactions or system events managed by JavaScript.

JavaScript Provides the Function

From the JavaScript side, setting up a callback is straightforward. You simply define a regular JavaScript function. This function will then be made available to your WebAssembly module during its initialization.

Think of it as giving your WASM module a direct line to call back into your JavaScript application when needed.

WASM Declares the Import

On the WebAssembly side (e.g., in Rust or C/C++), you need to declare that your module expects to import a function from its host environment (JavaScript).

  • In Rust, you use the #[wasm_bindgen] attribute with an extern "C" block.
  • This declaration specifies the function's name and its expected signature (parameters and return type).
  • It tells the WASM compiler that this function call will be resolved externally by JavaScript.

Rust Code: Importing JavaScript

Let's look at a Rust example. We'll import a JavaScript function named logMessageFromWasm. When Rust calls this, the corresponding JS function will execute.

/* lib.rs */
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
    // Imports a JS function named 'logMessageFromWasm'
    // It takes a string and returns nothing.
    #[wasm_bindgen(js_name = logMessageFromWasm)]
    fn log_message_from_wasm(s: &str);
}

#[wasm_bindgen]
pub fn call_js_log() {
    log_message_from_wasm("Hello from Rust!");
}

Running the Callback (JS + Rust)

To run the Rust code from the previous scene, we compile it to a .wasm module and use wasm-bindgen's glue code. Then, we define our JavaScript callback and load the WASM.

Check your browser's developer console after running!

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>WASM Callback Demo</title>
</head>
<body>
    <h1>Check console for WASM message!</h1>
    <script type="module">
        // Assuming 'pkg/rust_wasm_module.js' is generated by wasm-pack
        import init, { call_js_log } from './pkg/rust_wasm_module.js';

        // Define the JavaScript function that WASM will call
        window.logMessageFromWasm = (message) => {
            console.log("JS received:", message);
        };

        async function run() {
            await init(); // Initialize the WASM module
            call_js_log(); // Call the Rust function, which calls JS
        }

        run();
    </script>
</body>
</html>

Passing Data to Callbacks

Callbacks are not just for simple notifications; they can also pass data from your WebAssembly module back to JavaScript. This is crucial for returning results or providing context.

  • Primitive Types: Numbers (integers, floats) and booleans are passed directly.
  • Strings: With wasm-bindgen, Rust strings (`&str`) are efficiently converted to JavaScript strings.
  • Complex Objects: For more intricate data structures, `wasm-bindgen` provides mechanisms for seamless serialization and deserialization.

Callback with Arguments (Rust)

Let's enhance our Rust example to pass a number back to JavaScript. The `log_number_from_wasm` function is imported, expecting an integer argument.

Our Rust function `calculate_and_log` will perform a sum and then pass the result to this JS callback.

/* lib.rs */
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
    // Imports a JS function that takes an i32 number
    #[wasm_bindgen(js_name = logNumberFromWasm)]
    fn log_number_from_wasm(num: i32);
}

#[wasm_bindgen]
pub fn calculate_and_log(a: i32, b: i32) {
    let result = a + b;
    log_number_from_wasm(result); // Call JS with the calculated result
}

Running Callback with Arguments

Here's the JavaScript setup for the previous Rust example. Notice how the `window.logNumberFromWasm` function now accepts a numeric argument, which it then prints to the console.

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>WASM Callback Args Demo</title>
</head>
<body>
    <h1>Check console for calculated result!</h1>
    <script type="module">
        import init, { calculate_and_log } from './pkg/rust_wasm_module.js';

        // This JS function will receive a number from WASM
        window.logNumberFromWasm = (number) => {
            console.log("JS received result:", number);
        };

        async function run() {
            await init();
            calculate_and_log(10, 20); // Call Rust with arguments 10 and 20
        }

        run();
    </script>
</body>
</html>

Common Callback Scenarios

Custom callbacks are incredibly versatile and enable WASM to integrate smoothly with the browser's environment. Some common use cases include:

  • User Interface Updates: Notifying JS to update elements after a WASM computation is complete.
  • Browser API Access: Requesting JS to use `localStorage`, `fetch`, or directly manipulate the DOM.
  • Event Handling: Allowing WASM to react to user input or browser events processed by JS.
  • Logging and Debugging: Sending detailed messages to the browser console from within WASM for monitoring.

Quick Check on Callbacks

Understanding how to declare and use imported functions is key to effective WASM-JS communication.

Recap: Custom JS Callbacks

You've learned how to enable your WebAssembly modules to call back into JavaScript!

  • WASM modules can import and call JavaScript functions.
  • wasm-bindgen simplifies this process in Rust, allowing type-safe data exchange.
  • Callbacks are crucial for UI updates, accessing browser APIs, and logging from WASM.

This powerful pattern makes WASM applications more dynamic and integrated with the web environment. Keep experimenting!

자주 묻는 질문

“사용자 지정 JavaScript 콜백” 강의는 무료인가요?

네 — “사용자 지정 JavaScript 콜백” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebAssembly (WASM) for High Performance Apps 강의 전체를 잠금 해제할 수 있습니다. WebAssembly (WASM) for High Performance Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

“사용자 지정 JavaScript 콜백”에서 뭘 배우나요?

WebAssembly 모듈 내부에서 호출할 수 있는 사용자 지정 JavaScript 함수를 설계하고 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 WebAssembly (WASM) for High Performance Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

WebAssembly (WASM) for High Performance Apps을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 WebAssembly (WASM) for High Performance Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“사용자 지정 JavaScript 콜백” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 WebAssembly (WASM) for High Performance Apps 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 WebAssembly (WASM) for High Performance Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. WASM을 활용한 비동기 작업
  2. 사용자 지정 JavaScript 콜백
  3. 오류 처리 및 예외
  4. JS/WASM 경계에서 메모리와 형식 지정 배열 공유
← WebAssembly (WASM) for High Performance Apps(으)로 돌아가기