Ionic 4 how to call parent functions from popover menu

I have a popover menu, and I want each menu item to call a function from the main page. For instance, the main page is main-page.ts and the popover is popover.ts accessible from the top-right menu (it contains a number of items including ‘add new’). Now, main-page.ts contains an AddNew() function (as well as other functions listed in the popover menu), and when I open the popover menu and click ‘add new’, I want the AddNew() function to be called.

How do I implement that? I tried passing AddNew as a componentProps parameter in this.popoverController.create({…}), then in popover.ts used navparams to access it. But when the menu opens, it executes AddNew() immediately (and other functions passed in componentProps). Am I doing it correctly, or am I missing something?

Thanks.

1 Like

Figured it out, for anyone else interested.

Just pass ‘this’ as a parameter to the popover as componentProps: {homeref:this}, then access the functions in the popover via this.navParams.data.homeref.addNew();

1 Like

Passing this around is a giant red flag to me. I think it makes code very hard to read, test and understand. I get that JavaScript isn’t a true OO language, but at least attempting to respect encapsulation makes it easier to isolate problems.

How about having a command service that exposes some sort of Subject? The popover can inject that service and call next, while components that need to react can subscribe to it and do so accordingly.

Thanks for the update. I agree that passing this isn’t the best way, and is quite inefficient.
I’m unfamiliar with subjects (what are they??), so I’ll have to read up on it. Can you point me to a good tutorial on creating services to expose subjects in Ionic?

Is creating a service to expose a subject the way you’d do what I was trying to do (have a popup menu item call a parent’s function)?

RxJS thingies that let you make your own Observables easily.

It would probably be my second choice. I think the first thing I would try to do is to use onDidDismiss to pass back some sort of scalar (like a string indicating which button was pressed). That way, the popover only concerns itself with returning that value, and all the logic involving the component that spawned the popover stays in that class’s controller.

Use events it’s very simple…