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

Add ability to get registered data #3707

Closed
wants to merge 1 commit into from
Closed

Add ability to get registered data #3707

wants to merge 1 commit into from

Conversation

apih
Copy link

@apih apih commented Aug 12, 2023

This PR adds the ability to get registered data in Alpine.data(). This will allow a use case like this:

Alpine.data('Component1', {
  // bla bla
});

Alpine.data('Component2', {
  // bla bla
});

Alpine.data('Component3', {
  ...Alpine.data('Component1'),
  ...Alpine.data('Component2'),
});

@ekwoka
Copy link
Contributor

ekwoka commented Aug 12, 2023

You can just do that in the x-data

x-data="{...Component1, Component2}"

Just know this will break getters/setters

Also,

Alpine.data('Component3', () => {
   ...this.Component1(),
   ...this.Component2()
})

with

x-data="Component3"

should actually work (and still break getters/setters)

a utility component liek

Alpine.data("merge", (...components: object[]) => {
    return components.reduce((acc, obj) => {
      Object.defineProperties(acc, Object.getOwnPropertyDescriptors(obj));
      return acc;
    }, {});
  });

can be nice to merge components similar to spreading, but maintaining getters and setters, and this references, and such.

@apih
Copy link
Author

apih commented Aug 13, 2023

I am not aware that getters and setters will break when merged using spread operator. Mainly because I rarely use getters and setters. Will need to be careful in the future then.

@ekwoka
Copy link
Contributor

ekwoka commented Aug 13, 2023

Yeah, it makes sense when you think about it. If you enumerate the properties and values on an object, getters won't be getters, they will be the key and the value got from running that getter at that moment.

similarly, setters aren't enumerable at all.

the defineProperties method actually finds out the full description of the property (enumerable? configurable? read only? getter? setter?) and replicates all of that to the new object.

@calebporzio
Copy link
Collaborator

Good insight @ekwoka - 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