htmx icon indicating copy to clipboard operation
htmx copied to clipboard

[Docs] fix ui example with arrow function for `this` Binding

Open lloydlobo opened this issue 1 year ago • 1 comments

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 this binding in the onClick attribute'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 this confusion: They automatically inherit the this context, eliminating complexities.
  • Lexical scope: This fixes the this binding within the lexical scope, ensuring that this is bound to the button instead of the window.
  • 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');
}

Animation_htmx_arrow_fn

lloydlobo avatar Jan 29 '24 10:01 lloydlobo

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 😅

Telroshan avatar Feb 25 '24 20:02 Telroshan