Skip to content

Fix function assignments in x-init#4776

Closed
khepin wants to merge 3 commits intoalpinejs:mainfrom
khepin:initfn
Closed

Fix function assignments in x-init#4776
khepin wants to merge 3 commits intoalpinejs:mainfrom
khepin:initfn

Conversation

@khepin
Copy link

@khepin khepin commented Mar 19, 2026

See: #4775

During x-init if creating an arrow function to assign to a property (x-init="$el.fn = () => { flag = true }"), it will be executed immediately (interpreted as a block and not a function).
If a statement precedes that declaration, it is interpreted as a function and not executed immediately (x-init="0; $el.fn = () => { flag = true }")

Minimal repro HTML:

	<html>
		<head>
			<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3/dist/cdn.min.js"></script>
		</head>
		<body>
			<h2>Alpine x-init arrow function bug</h2>
			<p>Bug: flag should be "false" but shows "true"</p>
			<div x-data="{ flag: false }" x-init="$el.fn = () => { flag = true }">
				flag = <span x-text="flag"></span>
			</div>
			<p>Workaround: prepend a no-op statement</p>
			<div x-data="{ flag: false }" x-init="0; $el.fn = () => { flag = true }">
				flag = <span x-text="flag"></span>
			</div>
		</body>
	</html>

Result:

Alpine x-init arrow function bug
Bug: flag should be "false" but shows "true"

flag = true
Workaround: prepend a no-op statement

flag = false

I would expect both of those to give the same result, and I would expect both to function like the second case (prepended statement).

resolution

Adds a regex in generateFunctionFromString to correctly recognize those situations.

@khepin
Copy link
Author

khepin commented Mar 19, 2026

Ooof. Looks like I got some autoformatter thing in there. Gonna fix that.

@ekwoka
Copy link
Contributor

ekwoka commented Mar 23, 2026

feels messy...but it does make some sense.

the alternative is in userland just putting ; at the end of the expression (i think)

The ternary indentation in normalRawEvaluator was changed by an
autoformatter but is unrelated to the fix. This restores the original
indentation to keep the PR diff focused on the actual change.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@calebporzio
Copy link
Collaborator

idk, i see what you're saying but I don't love the implementation. I think I'm going to close until more report this and a better implemenation comes across. thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants