代码之家  ›  专栏  ›  技术社区  ›  ginad

如何在go-app组件中执行javascript代码

  •  0
  • ginad  · 技术社区  · 2 月前

    我正在启动一个新项目,看到了一个非常有趣的GO库,它有点类似于fasthtml,叫做GO-app。

    我很难执行像console.log或alert这样的简单JS命令。还是我错过了什么?

    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)
    }
    
    1 回复  |  直到 2 月前
        1
  •  1
  •   Sahadev    2 月前

    如果可行,请尝试以下操作:

    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)
    }