-
-
Notifications
You must be signed in to change notification settings - Fork 248
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #180 from kevanstannard/this-decorator-syntax
Add @this decorator to syntax lookup
- Loading branch information
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
--- | ||
id: "this-decorator" | ||
keywords: ["this", "decorator"] | ||
name: "@this" | ||
summary: "This is the `@this` decorator." | ||
category: "decorators" | ||
--- | ||
|
||
The `@this` decorator may be used to bind to an **external** callback function that require access to a `this` context. | ||
|
||
### Example | ||
|
||
<CodeTab labels={["ReScript", "JS Output"]}> | ||
|
||
```res | ||
type counter | ||
// Function to create an empty object | ||
@new external create: unit => counter = "Object" | ||
// Functions that set and get a "value" property | ||
@set external setValue: (counter, int) => unit = "value" | ||
@get external getValue: counter => int = "value" | ||
// Functions that create "increment" and "decrement" function properties which have access to "this" | ||
@set external setIncrement: (counter, @this (counter, int) => unit) => unit = "increment" | ||
@set external setDecrement: (counter, @this (counter, int) => unit) => unit = "decrement" | ||
// Use the functions above to create a counter instance | ||
let counter = create() | ||
setValue(counter, 0) | ||
setIncrement(counter, @this (me, amount) => me->setValue(me->getValue + amount)) | ||
setDecrement(counter, @this (me, amount) => me->setValue(me->getValue - amount)) | ||
``` | ||
|
||
```js | ||
var counter = new Object() | ||
|
||
counter.value = 0 | ||
|
||
counter.increment = function (amount) { | ||
var me = this | ||
me.value = (me.value + amount) | 0 | ||
} | ||
|
||
counter.decrement = function (amount) { | ||
var me = this | ||
me.value = (me.value - amount) | 0 | ||
} | ||
``` | ||
|
||
</CodeTab> | ||
|
||
### References | ||
|
||
* [Modeling `this`-based Callbacks](/docs/manual/latest/bind-to-js-function#modeling-this-based-callbacks) |