Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: Passing a struct into call. #534

Closed
4ydx opened this issue Oct 14, 2016 · 2 comments
Closed

Question: Passing a struct into call. #534

4ydx opened this issue Oct 14, 2016 · 2 comments
Labels

Comments

@4ydx
Copy link
Contributor

4ydx commented Oct 14, 2016

Wondering how one can pass a struct into Call and have it produce a dictionary with lowercase keys rather than uppercase exported keys.

package main

import (
  "github.com/gopherjs/gopherjs/js"
  "github.com/gopherjs/jquery"
)

var jQ = jquery.NewJQuery

type A struct {
  C string
}

func main() {
  jQ().Ready(func() {
    a := A{C: "test"}
    js.Global.Call("alert", a)
  })
}

When evaluating in the console this gives:

a
Object { $val: Object, C: "test" }
$externalize(a, A)
Object { C: "test" }

I want Object { c: "test" }. No doubt I am missing something obvious.

@myitcv
Copy link
Member

myitcv commented Oct 14, 2016

@4ydx

I don't think there is currently a way of doing this without using a struct with a special *js.Object field in position zero; see the gotchas wiki for more details.

Consider (playground link):

package main

import (
    "github.com/gopherjs/gopherjs/js"
)

type S1 struct {
    C1 string `js:"c1"` // tag has no effect
}

type S2 struct {
    *js.Object

    C1 string `js:"c1"`  // tag has effect because of *js.Object at position 0
    C2 string
}

func main() {
    s1 := S1{C1: "S1 C1"}

    // output will be: Object {C1: "S1 C1"}
    js.Global.Get("console").Call("log", "s1", s1)

    // s2 must be a *S2; see the gotchas wiki
    s2 := &S2{Object: js.Global.Get("Object").New()} 

    // this js-tagged field must be set separate from the initialization
    // of s2; again, see the gotchas wiki
    s2.C1 = "S2 C1"

    s2.C2 = "S2 C2"

    // output will be: Object {c1: "S2 C1"}
    js.Global.Get("console").Call("log", "s2", s2)
}

But in converting your type to have a *js.Object field in position zero, beware of the gotcha that starts "In structs with *js.Object fields, the object exists in two parts..."

I'm looking to try and improve the gotchas wiki to explain this better, but I also think the use of js: tags could be made more general as you're alluding to here.

@4ydx
Copy link
Contributor Author

4ydx commented Oct 14, 2016

Thanks very much. That clarifies things.

@4ydx 4ydx closed this as completed Oct 14, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants