Arguments passed to Alpine.data() are used to automatically call init() #1521
Replies: 4 comments 23 replies
-
@johndwells I believe one of the main reasons |
Beta Was this translation helpful? Give feedback.
-
I have changed my components that used arguments to take dataset attributes instead. So, before: <div x-data="myComponent({ foo: true, spam: 'world' })"> After: <div x-data="myComponent" data-foo="true" data-spam="world"> function myComponent() {
return {
foo: null,
spam: "",
init() {
this.foo = !! this.$el.dataset.foo;
this.spam = this.$el.dataset.spam;
}
};
} The only thing I don't like about this pattern is that passing a bool via an HTML string is a bit fraught, but otherwise it's cool. |
Beta Was this translation helpful? Give feedback.
-
Interesting points here. There's a lot of tradeoffs however. As far as the CSP stuff, I don't think that prevents us from offering an API like this: Not an obvious answer here, so still interested to here more proposed APIs and thoughts on this. |
Beta Was this translation helpful? Give feedback.
-
I have a scenario where I need to pull data off the <div x-data="initialize(42)">
<!-- ... -->
</div>
<div x-data="initialize(43)">
<!-- ... -->
</div> initialize(id) {
return {
...window[id]
};
} It would be nice if <div x-data="component(42)">
<!-- ... -->
</div>
<div x-data="initialize(43)">
<!-- ... -->
</div> Alpine.data('component', (id) => ({
...window[id]
})); |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Related discussion: #1500
Being able to create reusable components with
Alpine.data()
is great, but the common pattern with reusable components is configurable options/flags when running them. Take for example a custom component that initializes a Flickity slideshow, where one instance page dots are visible, and in another they are hidden...Also, when a component has an
init()
function defined, Alpine will automatically call that function when initializing the component. However because of this automatic call, we cannot defineinit()
to accept parameters, and then call it viax-init="init(param1, param2)"
because it will be called twice.What I would propose is that passing any options to
component()
would be used when automatically callinginit()
. The resulting markup would look like:<div x-data="component(param1, param2)"></div>
Thoughts?
Beta Was this translation helpful? Give feedback.
All reactions