Skip to content

Commit

Permalink
update sort docs
Browse files Browse the repository at this point in the history
  • Loading branch information
calebporzio committed Apr 10, 2024
1 parent 251f593 commit 85dd889
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions packages/docs/src/en/plugins/sort.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,26 +78,36 @@ The primary API for using this plugin is the `x-sort` directive. By adding `x-so
You can react to sorting changes by passing a handler function to `x-sort` and adding keys to each item using `x-sort:key`. Here is an example of a simple handler function that shows an alert dialog with the changed item's key and its new position:

```alpine
<div x-data="{ handle(key, position) { alert(key + ' - ' + position)} }">
<ul x-sort="handle">
<ul x-sort="alert($key + ' - ' + $position)">
<li x-sort:key="1">foo</li>
<li x-sort:key="2">bar</li>
<li x-sort:key="3">baz</li>
</ul>
```

<!-- START_VERBATIM -->
<div x-data>
<ul x-sort="alert($key + ' - ' + $position)">
<li x-sort:key="1">foo</li>
<li x-sort:key="2">bar</li>
<li x-sort:key="3">baz</li>
</ul>
</div>
```
<!-- END_VERBATIM -->

<!-- START_VERBATIM -->
<div x-data="{ handle(key, position) { alert(key + ' - ' + position)} }">
The `x-sort` handler will be called every time the sort order of the items change. The `$key` magic will contain the key of the sorted element (derived from `x-sort:key`), and `$position` will contain the new position of the item (staring at index `0`).

You can also pass a handler function to `x-sort` and that function will receive the `key` and `position` as the first and second parameter:

```alpine
<div x-data="{ handle: (key, position) => { ... } }">
<ul x-sort="handle">
<li x-sort:key="1">foo</li>
<li x-sort:key="2">bar</li>
<li x-sort:key="3">baz</li>
</ul>
</div>
<!-- END_VERBATIM -->

As you can see, the `key` and `position` parameters are passed into the handler function on every sorting change. The `key` parameter is the value provided to `x-sort:key`, and the `position` parameter is its new position in the list of children (starting at index `0`).
```

Handler functions are often used to persist the new order of items in the database so that the sorting order of a list is preserved between page refreshes.

Expand Down

0 comments on commit 85dd889

Please sign in to comment.