|
1 | 1 | //go:build js
|
| 2 | +// +build js |
2 | 3 |
|
3 |
| -package main |
| 4 | +package wasm |
4 | 5 |
|
5 |
| -import ( |
6 |
| - "fmt" |
7 |
| - "syscall/js" |
8 |
| -) |
| 6 | +import "syscall/js" |
9 | 7 |
|
10 |
| -func wireFunctions() { |
11 |
| - js.Global().Set("increment", js.FuncOf(increment)) |
12 |
| - js.Global().Set("log", js.FuncOf(logInfo)) |
13 |
| - js.Global().Set("send", js.FuncOf(send)) |
| 8 | +func (w *WASM) wireFunctions() { |
| 9 | + js.Global().Set("log", js.FuncOf(w.logInfo)) |
| 10 | + js.Global().Set("sendMessage", js.FuncOf(w.sendMessage)) |
14 | 11 | }
|
15 | 12 |
|
16 |
| -func increment(this js.Value, args []js.Value) any { |
17 |
| - if len(args) == 0 { |
18 |
| - return "exactly one argument is required" |
19 |
| - } |
20 |
| - arg := args[0].Int() |
21 |
| - return arg + 1 |
22 |
| -} |
23 |
| - |
24 |
| -func send(this js.Value, args []js.Value) any { |
25 |
| - if len(args) == 0 { |
26 |
| - return "at least one argument is required" |
27 |
| - } |
28 |
| - arg := args[0].String() |
29 |
| - return arg |
30 |
| -} |
31 |
| - |
32 |
| -func logInfo(this js.Value, args []js.Value) any { |
33 |
| - if _rootLogger == nil { |
| 13 | +func (w *WASM) logInfo(this js.Value, args []js.Value) any { |
| 14 | + if w.logger == nil { |
34 | 15 | println("ERROR: no logger available")
|
35 | 16 | return nil
|
36 | 17 | }
|
37 | 18 | if len(args) == 0 {
|
38 |
| - _rootLogger.Warnf("at least one argument is required") |
| 19 | + w.logger.Warnf("at least one argument is required") |
39 | 20 | return nil
|
40 | 21 | }
|
41 | 22 | msg := args[0].String()
|
42 |
| - cleanArgs := make([]any, 0, len(args)-1) |
43 |
| - for _, x := range args[1:] { |
44 |
| - switch x.Type() { |
45 |
| - case js.TypeString: |
46 |
| - cleanArgs = append(cleanArgs, x.String()) |
47 |
| - case js.TypeBoolean: |
48 |
| - cleanArgs = append(cleanArgs, x.Bool()) |
49 |
| - case js.TypeNumber: |
50 |
| - cleanArgs = append(cleanArgs, x.Float()) |
51 |
| - case js.TypeNull: |
52 |
| - cleanArgs = append(cleanArgs, "<null>") |
53 |
| - default: |
54 |
| - cleanArgs = append(cleanArgs, fmt.Sprintf("unhandled type [%T]", x)) |
55 |
| - } |
56 |
| - } |
57 |
| - _rootLogger.Infof(msg, cleanArgs...) |
| 23 | + w.logger.Infof(msg, convertArgs(args[1:])...) |
58 | 24 | return nil
|
59 | 25 | }
|
| 26 | + |
| 27 | +func (w *WASM) sendMessage(this js.Value, args []js.Value) any { |
| 28 | + if len(args) != 1 { |
| 29 | + return "exactly one argument is required" |
| 30 | + } |
| 31 | + arg := args[0].Get("t").String() |
| 32 | + w.logger.Infof("got message of type [%s]", arg) |
| 33 | + return arg |
| 34 | +} |
0 commit comments