Skip to content

Commit 2aec0f6

Browse files
authored
Merge pull request #180 from kevanstannard/this-decorator-syntax
Add @this decorator to syntax lookup
2 parents eaeeb35 + 3dafd59 commit 2aec0f6

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

misc_docs/syntax/decorator_this.mdx

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
---
2+
id: "this-decorator"
3+
keywords: ["this", "decorator"]
4+
name: "@this"
5+
summary: "This is the `@this` decorator."
6+
category: "decorators"
7+
---
8+
9+
The `@this` decorator may be used to bind to an **external** callback function that require access to a `this` context.
10+
11+
### Example
12+
13+
<CodeTab labels={["ReScript", "JS Output"]}>
14+
15+
```res
16+
type counter
17+
18+
// Function to create an empty object
19+
@new external create: unit => counter = "Object"
20+
21+
// Functions that set and get a "value" property
22+
@set external setValue: (counter, int) => unit = "value"
23+
@get external getValue: counter => int = "value"
24+
25+
// Functions that create "increment" and "decrement" function properties which have access to "this"
26+
@set external setIncrement: (counter, @this (counter, int) => unit) => unit = "increment"
27+
@set external setDecrement: (counter, @this (counter, int) => unit) => unit = "decrement"
28+
29+
// Use the functions above to create a counter instance
30+
let counter = create()
31+
setValue(counter, 0)
32+
setIncrement(counter, @this (me, amount) => me->setValue(me->getValue + amount))
33+
setDecrement(counter, @this (me, amount) => me->setValue(me->getValue - amount))
34+
```
35+
36+
```js
37+
var counter = new Object()
38+
39+
counter.value = 0
40+
41+
counter.increment = function (amount) {
42+
var me = this
43+
me.value = (me.value + amount) | 0
44+
}
45+
46+
counter.decrement = function (amount) {
47+
var me = this
48+
me.value = (me.value - amount) | 0
49+
}
50+
```
51+
52+
</CodeTab>
53+
54+
### References
55+
56+
* [Modeling `this`-based Callbacks](/docs/manual/latest/bind-to-js-function#modeling-this-based-callbacks)

0 commit comments

Comments
 (0)