-
Notifications
You must be signed in to change notification settings - Fork 6
/
closure.go
91 lines (73 loc) · 2.55 KB
/
closure.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package javascript
import (
"encoding/gob"
"encoding/json"
"strings"
)
// NewClosure creates a new Closure object.
func NewClosure(body string, args ...string) Closure {
return Closure{body, args}
}
// Closure represents a javascript function pointer that can be called by javascript at a later time.
type Closure struct {
// Body is the body javascript of the Closure
Body string
// Args are the names of the arguments in the argument list of the Closure
Args []string
}
// JavaScript implements the JavaScripter interface and returns the Closure as javascript code.
func (c Closure) JavaScript() string {
var args string
if c.Args != nil {
args = strings.Join(c.Args, ", ")
}
return "function(" + args + ") {" + c.Body + "}"
}
// MarshalJSON implements the json.Marshaller interface.
// The output of this is designed to be unpacked by the goradd.js javascript file during Ajax calls.
func (c Closure) MarshalJSON() (buf []byte, err error) {
var obj = map[string]interface{}{}
obj[JsonObjectType] = "closure"
obj["func"] = c.Body
obj["params"] = c.Args
buf, err = json.Marshal(obj)
return
}
// NewClosureCall creates a new ClosureCall.
func NewClosureCall(body string, context string, args ...string) ClosureCall {
return ClosureCall{body, context, args}
}
// ClosureCall represents the result of a javascript Closure that is called immediately.
// context will become the "this" variable inside the Closure when called.
type ClosureCall struct {
// Body is the body javascript of the Closure
Body string
// Context is what will become the "this" var inside the Closure when called. Specifying "this" will bring the "this" from the outer context in to the Closure.
Context string
// Args are the names of the arguments in the argument list of the Closure
Args []string
}
// JavaScript implements the JavaScripter interface and returns the Closure as javascript code.
func (c ClosureCall) JavaScript() string {
var args string
if c.Args != nil {
args = strings.Join(c.Args, ", ")
}
return "(function(" + args + ") {" + c.Body + "}).call(" + c.Context + ")"
}
// MarshalJSON implements the json.Marshaller interface.
// The output of this is designed to be unpacked by the goradd.js javascript file.
func (c ClosureCall) MarshalJSON() (buf []byte, err error) {
var obj = map[string]interface{}{}
obj[JsonObjectType] = "closure"
obj["func"] = c.Body
obj["params"] = c.Args
obj["call"] = c.Context
buf, err = json.Marshal(obj)
return
}
func init() {
// Register objects so they can be serialized
gob.Register(Closure{})
gob.Register(ClosureCall{})
}