소스 검색

Merge pull request #1498 from ryangjchandler/fix/binding-undefined-value

fix: binding undefined nested value
Caleb Porzio 4 년 전
부모
커밋
f5807a1414
2개의 변경된 파일12개의 추가작업 그리고 0개의 파일을 삭제
  1. 3 0
      packages/alpinejs/src/directives/x-bind.js
  2. 9 0
      tests/cypress/integration/directives/x-bind.spec.js

+ 3 - 0
packages/alpinejs/src/directives/x-bind.js

@@ -13,6 +13,9 @@ directive('bind', (el, { value, modifiers, expression, original }, { effect }) =
     let evaluate = evaluateLater(el, expression)
     let evaluate = evaluateLater(el, expression)
 
 
     effect(() => evaluate(result => {
     effect(() => evaluate(result => {
+        // If nested object key is undefined, set the default value to empty string.
+        if (result === undefined && expression.match(/\./)) result = ''
+
         mutateDom(() => bind(el, value, result, modifiers))
         mutateDom(() => bind(el, value, result, modifiers))
     }))
     }))
 })
 })

+ 9 - 0
tests/cypress/integration/directives/x-bind.spec.js

@@ -9,6 +9,15 @@ test('sets attribute bindings on initialize',
     ({ get }) => get('span').should(haveAttribute('foo', 'bar'))
     ({ get }) => get('span').should(haveAttribute('foo', 'bar'))
 )
 )
 
 
+test('sets undefined nested keys to empty string',
+    html`
+        <div x-data="{ nested: {} }">
+            <input x-bind:value="nested.field">
+        </div>
+    `,
+    ({ get }) => get('input').should(haveAttribute('value', ''))
+)
+
 test('style attribute bindings are added by string syntax',
 test('style attribute bindings are added by string syntax',
     html`
     html`
         <div x-data="{ initialClass: 'foo' }">
         <div x-data="{ initialClass: 'foo' }">