Browse Source

Support normal HTML attribute bindings from x-bind

Caleb Porzio 3 years ago
parent
commit
b55e3e334a

+ 7 - 1
packages/alpinejs/src/directives.js

@@ -33,6 +33,12 @@ export function directives(el, attributes, originalAttributeOverride) {
     })
 }
 
+export function attributesOnly(attributes) {
+    return Array.from(attributes)
+        .map(toTransformedAttributes())
+        .filter(attr => ! outNonAlpineAttributes(attr))
+}
+
 let isDeferringHandlers = false
 let directiveHandlerStacks = new Map
 let currentHandlerStackKey = Symbol()
@@ -107,7 +113,7 @@ export let startingWith = (subject, replacement) => ({ name, value }) => {
 
 export let into = i => i
 
-function toTransformedAttributes(callback) {
+function toTransformedAttributes(callback = () => {}) {
     return ({ name, value }) => {
         let { name: newName, value: newValue } = attributeTransformers.reduce((carry, transform) => {
             return transform(carry)

+ 9 - 1
packages/alpinejs/src/directives/x-bind.js

@@ -1,4 +1,4 @@
-import { directive, directives, into, mapAttributes, prefix, startingWith } from '../directives'
+import { attributesOnly, directive, directives, into, mapAttributes, prefix, startingWith } from '../directives'
 import { evaluateLater } from '../evaluator'
 import { mutateDom } from '../mutation'
 import bind from '../utils/bind'
@@ -31,6 +31,14 @@ function applyBindingsObject(el, expression, original, effect) {
         getBindings(bindings => {
             let attributes = Object.entries(bindings).map(([name, value]) => ({ name, value }))
 
+            // Handle binding normal HTML attributes (non-Alpine directives).
+            attributesOnly(attributes).forEach(({ name, value }, index) => {
+                attributes[index] = {
+                    name: `x-bind:${name}`,
+                    value: `"${value}"`,
+                }
+            })
+
             directives(el, attributes, original).map(handle => {
                 cleanupRunners.push(handle.runCleanups)
 

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

@@ -308,6 +308,15 @@ test('can bind an object of directives',
     }
 )
 
+test('x-bind object syntax supports normal HTML attributes',
+    html`
+        <span x-data x-bind="{ foo: 'bar' }"></span>
+    `,
+    ({ get }) => {
+        get('span').should(haveAttribute('foo', 'bar'))
+    }
+)
+
 test('x-bind object syntax supports x-for',
     html`
         <script>