goprogressive-web-appsgo-wasmgo-app

How can I execute javascript codes in go-app component


I'm starting a new project and saw a very interesting library for GO which is somewhat similar to fasthtml called go-app.

I'm struggling to execute simple JS commands like console.log or alert. Or am I missing something?

type Button struct {
    app.Compo
}

func (b *Button) OnClick(ctx app.Context, e app.Event) {
    // NONE of these codes works when clicking the button.

    //e.JSValue().Call("alert", "e jsvalue call Button clicked!")
    //ctx.JSSrc().Call("alert", "ctx jssrc call Button clicked!")

    //app.Window().Get("alert").Call("window get call Hello world")
    //app.Window().Call("alert", "window call Button clicked!")
    app.Window().Get("console").Call("log", "window get call log")
}

func (b *Button) Render() app.UI {
    return app.Button().
        ID("button").
        Text("Click me!").
        OnClick(b.OnClick)
}

Solution

  • Try this if it will work:

    type Button struct {
        app.Compo
    }
    
    func (b *Button) OnClick(ctx app.Context, e app.Event) {
        // Access the window object and call the alert function
        app.Window().Call("alert", "Button clicked alert!")
    
        // Or directly access console.log from the window
        app.Window().Get("console").Call("log", "clicked!")
    }
    
    func (b *Button) Render() app.UI {
        return app.Button().
            ID("button").
            Text("Click Button!").
            OnClick(b.OnClick)
    }