Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared event handler for XML views with different controllers

Given two XML Views:

<mvc:View
  controllerName="my.namespace.controller.First"
  xmlns:mvc="sap.ui.core.mvc" 
  xmlns="sap.m">

  <Button press=".onBtnPress" />
</mvc:View>


<mvc:View
  controllerName="my.namespace.controller.Second"
  xmlns:mvc="sap.ui.core.mvc" 
  xmlns="sap.m">

  <Button press=".onBtnPress" />
</mvc:View>

As expected, the press event is handled by First.controller.js or Second.controller.js.

Instead of duplicating the event handler code or implementing handlers in each Controller to chain/hand off the work, I want to declare a shared event handler.

According to docs this should be possible, using a naming convention for the handler:

Names starting with a dot ('.') are always assumed to represent a method in the controller.

Names containing a dot at a later position are assumed to represent global functions and are resolved by calling jQuery.sap.getObject with the full name.

So I change the handler and declare a shared object, like so:

First.view.xml:

<Button press="my.namespace.Shared.onBtnPress" />

Shared.js:

jQuery.sap.declare("my.namespace.Shared");

  my.namespace.Shared = (function() {

    var onBtnPress = function() {
      console.log("button pressed");
    };

  return { onBtnPress : onBtnPress };
}());

Warning logged (debug sources) during view initialisation:

sap.ui.core.mvc.XMLView#__xmlview1: event handler function "my.namespace.Shared.onBtnPress" is not a function or does not exist in the controller. -

Calling jQuery.sap.getObject("my.namespace.Shared") yields undefined

Same issue when using sap.ui.define to make the object known.

like image 896
cjoy Avatar asked Aug 24 '26 00:08

cjoy


1 Answers

Since UI5 1.69, it has become easier to share JS modules in XML view and fragment.doc

Here is an example: https://embed.plnkr.co/5G80I5HWObCuM5cG

<mvc:View controllerName="..."
  xmlns:mvc="sap.ui.core.mvc"
  xmlns="sap.m"
  xmlns:core="sap.ui.core"
  core:require="{ onButtonPress: 'my/shared/onButtonPress' }">
  <Button text="Press" press="onButtonPress" />
</mvc:View>

As we can see, each button displays a different message depending on the view, even though the handler itself isn't included in the controller definition.

The this context is still the controller instance as documented in the topic Handling Events in XML Views:

As long as no event handler parameters are specified and regardless of where the function was looked up, it will be executed with the controller as the context object (this).

like image 79
Boghyon Hoffmann Avatar answered Aug 27 '26 00:08

Boghyon Hoffmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!