Skip to content

Allow x-init on child nodes#1015

Closed
inxilpro wants to merge 1 commit intoalpinejs:masterfrom
inxilpro:feature/moar-x-init
Closed

Allow x-init on child nodes#1015
inxilpro wants to merge 1 commit intoalpinejs:masterfrom
inxilpro:feature/moar-x-init

Conversation

@inxilpro
Copy link
Contributor

Right now x-init only fires on root components (i.e. DOM nodes with x-data attributes). This PR lets child nodes also add x-init calls.

The primary use-case is when Alpine code is being generated by a templating language, like Blade. Typically an Alpine component would just initialize all of its state in one x-init or x-data statement, but if you're composing functionality with templates, your initial state may be spread through the entire DOM tree.

The real-world use-case is that I'm working on an Algolia InstantSearch implementation in Blade and Alpine. Here's a sample of the API:

<x-instantsearch :application-id="demo">

  <!-- This needs to call addWidget() once and only once per <x-instantsearch> instance -->
  <x-instantsearch-refinement-list attribute="language" />

  <x-instantsearch-hits>
    <div x-text="hit.packageName"></div>
  </x-instantsearch-hits>

</x-instantsearch>

If x-init was called on all sub-components, the resulting code could look like:

<div x-data="{applicationId: 'demo'}" x-init="initInstantSearch">

  <div x-init="search.addWidget(instantsearch.connectors.connectRefinementList( ... ))">
    <!-- Any additional markup -->
  </div>

  <template x-for="hit in hits" :key="hit">
    <div x-text="hit.packageName"></div>
  </template>

</div>

@KevinBatdorf
Copy link
Contributor

Would this cause an issue with Alpine.clone()?

In case this doesn't get merged, or if you want the functionality now, you can add a magic helper to get (perhaps?) the behavior you want:
Code: https://gist.github.com/KevinBatdorf/e8b18ccb20463bc4297747e8a8bac7f2
Demo: https://codepen.io/KevinBatdorf/pen/RwGEdpr?editors=1011

**I put this together quickly so I haven't tested it much! You likely would want to customize it and iron out any edge cases you encounter.

@calebporzio
Copy link
Collaborator

Thanks for the PR @inxilpro, this makes a lot of sense, however I'm not going to merge it into this version for the sake of stability.

Fortunately, I've already added this functionality to V3 though, so it will be available when that comes out.

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