[Docs] fix ui example with arrow function for `this` Binding
Hey there! I identified a glitch in the documentation example at www/content/examples/confirm.md. Here's the situation:
What
- The current example has an issue with the
thisbinding in theonClickattribute's.then(function(arg){})handler. - To maintain clarity and avoid bugs, let's switch to an arrow function in the
.then((arg) => {})handler.
Proposed Change
<button
hx-get="/confirmed"
hx-trigger="confirmed"
- onClick="Swal.fire({ title: 'Confirm', text: 'Do you want to continue?' }).then(function(result){
+ onClick="Swal.fire({ title: 'Confirm', text: 'Do you want to continue?' }).then((result) => {
if (result.isConfirmed) {
htmx.trigger(this, 'confirmed');
}
})"
>
Click Me
</button>
References
Why
- No
thisconfusion: They automatically inherit thethiscontext, eliminating complexities. - Lexical scope: This fixes the
thisbinding within the lexical scope, ensuring thatthisis bound to thebuttoninstead of thewindow. - Modern JavaScript usage: The preferred approach for
.then()callbacks nowadays.
I have a proposed update for the documentation ~~(https://github.com/lloydlobo/htmx/commit/e169bde180faf5e47f8552bcb230fa293018e4e1)~~ (https://github.com/bigskysoftware/htmx/pull/2373/commits/b8a59b7efad141e0546f3cd50ed315badab59d46.) Can I can go ahead and submit a pull request?
Preview
The GIF demonstrates that clicking the button logs this to the console. The change ensures correct this binding, logging the specific button instead of the window.
if (result.isConfirmed) {
console.log(this);
htmx.trigger(this, 'confirmed');
}
Hey! Feel free to open documentation PRs (we require opening issues for new features but doc is ok), especially if the currently documented example doesn't work 😅