Browse Source

allow await in invalid expression wrapper (#3146)

* :test_tube: Adds failing text for await in invalid expressions

* :white_check_mark: Wraps invalid expressions in an async IIFE

* Trigger CI

Co-authored-by: Josh Hanley <josh@hitsystems.com.au>
Eric Kwoka 2 năm trước cách đây
mục cha
commit
2369462446

+ 1 - 1
packages/alpinejs/src/evaluator.js

@@ -73,7 +73,7 @@ function generateFunctionFromString(expression, el) {
         || /^[\n\s]*if.*\(.*\)/.test(expression)
         // Support expressions starting with "let/const" like: "let foo = 'bar'"
         || /^(let|const)\s/.test(expression)
-            ? `(() => { ${expression} })()`
+            ? `(async()=>{ ${expression} })()`
             : expression
 
     const safeAsyncFunction = () => {

+ 14 - 0
tests/cypress/integration/directives/x-on.spec.js

@@ -534,3 +534,17 @@ test('.dot modifier correctly binds event listener with namespace',
         get('span').should(haveText('baz'))
     }
 )
+
+test('handles await in handlers with invalid right hand expressions',
+    html`
+        <div x-data="{ text: 'original' }">
+            <button @click="let value = 'new string'; text = await Promise.resolve(value)"></button>
+            <span x-text="text"></span>
+        </div>
+    `,
+    ({ get }) => {
+        get('span').should(haveText('original'))
+        get('button').click()
+        get('span').should(haveText('new string'))
+    }
+)