Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: init() function doesn't have access to the parent scope #1874

Merged

Conversation

SimoTod
Copy link
Collaborator

@SimoTod SimoTod commented Jul 29, 2021

Bug description: The init function that gets called automatically doesn't have access to the parent scope while x-init does.

Mentioned in #1674 and #1711

Relevant changes:

Note:
I didn't run many tests for destroy since we might need a follow-up. In the current implementation, we call undo first and then destroy which means that the scope is removed before we call destroy. I believe they should be swapped but I'm not sure if it's been done on purpose so I didn't touch it in this PR.

@calebporzio
Copy link
Collaborator

Hey Simone, interesting - I wouldn't intuit that I have access to parent scope from anywhere inside a "data component" object.

I suppose this IS something available to you in any other method that is called from an element though yes?

@pomartel
Copy link

pomartel commented Aug 2, 2021

@calebporzio Yes, the parent scope is available from other methods. You can even rename the data component init function to initialize for example and then add x-init='initialize' to your markup and the parent scope will then be available. That's how I work around the bug for now while still using data components.

@pomartel
Copy link

pomartel commented Aug 2, 2021

By the way, the bug is not only there with Alpine.data() objects but regular components as well. I made a codepen that illustrates it (and the workaround): https://codepen.io/pomartel/pen/dyWjGpv

@SimoTod
Copy link
Collaborator Author

SimoTod commented Aug 2, 2021

Yeah, basically if you use x-init, you can access the parent scope since the directives uses evaluate while the auto init calls the function directly so it doesn't. If it's the expected behavior, feel free to close it.

@calebporzio
Copy link
Collaborator

Ok, good points. I'm merging this - thanks!

@calebporzio calebporzio merged commit 39c55e1 into alpinejs:main Aug 3, 2021
@piotrze
Copy link

piotrze commented Aug 7, 2021

@SimoTod Thanks! It was missing piece for my nested components.

@SimoTod SimoTod deleted the bug/init-cannot-access-parent-scope branch November 20, 2021 00:27
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.

None yet

4 participants