drws65968272 2017-02-03 10:30
浏览 87

Golang结构的双向绑定

TLDR: Can I register callback functions in golang to get notified if a struct member is changed?


I would like to create a simple two-way-binding between a go server and an angular client. The communication is done via websockets.

Example:

Go:

type SharedType struct {
    A int
    B string
}
sharedType := &SharedType{}
...
sharedType.A = 52

JavaScript:

var sharedType = {A: 0, B: ""};
...
sharedType.A = 52;

Idea:

In both cases, after modifying the values, I want to trigger a custom callback function, send a message via the websocket, and update the value on the client/server side accordingly.

The sent message should only state which value changed (the key / index) and what the new value is. It should also support nested types (structs, that contain other structs) without the need of transmitting everything.

On the client side (angular), I can detect changes of JavaScript objects by registering a callback function.

On the server side (golang), I could create my own map[] and slice[] implementations to trigger callbacks everytime a member is modified (see the Cabinet class in this example: https://appliedgo.net/generics/).

Within these callback-functions, I could then send the modified data to the other side, so two-way binding would be possible for maps and slices.

My Question:

I would like to avoid things like

sharedType.A = 52
sharedType.MemberChanged("A")
// or:
sharedType.Set("A", 52) //.. which is equivalent to map[], just with a predifined set of allowed keys

Is there any way in golang to get informed if a struct member is modified? Or is there any other, generic way for easy two-way binding without huge amounts of boiler-plate code?

  • 写回答

1条回答 默认 最新

  • douxishai8552 2017-02-03 11:42
    关注

    No, it's not possible.


    But the real question is: how do you suppose to wield all such magic in your Go program?

    Consider what you'd like to have would be indeed possible. Now an innocent assignment

    v.A = 42
    

    would—among other things—trigger sending stuff over a websocket connection to the client.

    Now what happens if the connection is closed (client disconnected), and the sending fails? What happens if sending fails to complete before a deadline is reached?

    OK, suppose you get it at least partially right and actual modification of the local field happens only if sending succeeds. Still, how should sending errors be handled?

    Say, what should happen if the third assignment in

     v.A = 42
     v.B = "foo"
     v.C = 1e10-23
    

    fails?

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?