Custom elements - share one view-model

Hi all,

Been trawling Google for who knows how long and I can’t seem to find a solution to this. Hopefully someone can help :slight_smile:

Let’s say I have a component containing two instances of a custom element, like this:

<template>
    <require from="my-custom-element"></require>

    <my-custom-element></my-custom-element>

    <!-- blah blah blah some more markup -->

    <my-custom-element></my-custom-element>
</template.

Within the view-model for this custom element, I have an event aggregator subscription set up. The subscription is making an API call to a backend service.

Now, I’ve noticed that because I have two instances of the custom element injected into my component, that the API call is being made twice. This is not desirable.

How do I get these two custom elements to just share one view-model, and hence one subscription? Is that possible?

Thanks!

1 Like

I think if the purpose is to have a single subscription, for multiple instances, maybe the instances shouldn’t be handling the subscription directly?
You can do this via a shared service, or a handler among all the instances of <my-custom-element/> and let it do that, with a queue, so that it won’t fire for all the instances.

How do I get these two custom elements to just share one view-model, and hence one subscription? Is that possible?

It’s not easy to imagine having only single instance for all of your custom element usages. It may not be feasible.

1 Like

Yeah I figured I might have to change things up here, I’ve started experimenting with a sort of “master controller” component for my-custom-element but it’s led to quite a refactor. I was just hoping there was an easier solution.

1 Like