GopherJS bindings for built-in JavaScript functions
JavaScript has a small number of built-in
functions
to handle some common day-to-day tasks. This package providers wrappers around
some of these functions for use in GopherJS.
It is worth noting that in many cases, using Go’s equivalent functionality
(such as that found in the net/url package)
may be preferable to using this package, and will be a necessity any time you
wish to share functionality between front-end and back-end code.
Not all JavaScript built-in functions make sense or are useful in a Go
environment. The table below shows each of the JavaScript built-in functions,
and its current state in this package.
Name | Supported | Comment |
---|---|---|
eval() | — | |
uneval() | — | |
isFinite() | yes | |
isNaN() | yes | |
parseFloat() | TODO? | See note below |
parseInt() | TODO? | See note below |
decodeURI() | yes | |
decodeURIComponent() | yes | |
encodeURI() | yes | |
encodeURIComponent() | yes | |
escape() | — | deprecated circa 2000 |
Number() | — | See note below |
String() | — | Use js.Object.String() |
unescape() | — | deprecated circa 2000 |
typeof operator | yes | |
instanceof operator | yes |
parseInt()
to Go’s (u?)int(8|16|32|64)
types,parseFloat()
Go’s float(32|64)
or complex(64|128)
needs toNaN
NaN
result probably needs to be converted to a proper GoGet or update this package and dependencies with:
go get -u -d -tags=js github.com/gopherjs/jsbuiltin
This is a modified version of the Pet example in the main GopherJS documentation,
to accept and return URI-encoded pet names using the jsbuiltin package.
package main
import (
"github.com/gopherjs/gopherjs/js"
"github.com/gopherjs/jsbuiltin"
)
func main() {
js.Global.Set("pet", map[string]interface{}{
"New": New,
})
}
type Pet struct {
name string
}
func New(name string) *js.Object {
return js.MakeWrapper(&Pet{name})
}
func (p *Pet) Name() string {
return jsbuiltin.EncodeURIComponent(p.name)
}
func (p *Pet) SetName(uriComponent string) error {
name, err := jsbuiltin.DecodeURIComponent(uriComponent)
if err != nil {
// Malformed UTF8 in uriComponent
return err
}
p.name = name
return nil
}