Question

What are the best practices for defining a custom pseudo-event in SAPUI5/OpenUI5?

For example, let's say I wanted to fire an event on an extended sap.m.Button when pressed and held for several seconds.

Was it helpful?

Solution

I'm not sure if there are yet any 'best practices', I really think there's only 'one' practice ;-) But I'm eager to learn any other takes, so if anyone can comment on this, please do not hesitate!

I think the general idea is just to define your event; the UI5 framework then automatically generates methods for registering (attach<YourEvent>), deregistering (detach<YourEvent>), and firing events (fire<YourEvent>).

For example:

return ControlToExtend.extend("your.custom.Control", {
  metadata: {
    properties: {
      // etc...
    },
    aggregations: {
      "_myButton": {
        type: "sap.m.Button",
        multiple : false,
        visibility: "hidden"
      },
      // etc...
    },
    associations: {
      // etc...
    },
    events: {
      yourCustomEvent: {
        allowPreventDefault: true,
        parameters: {
          "passAlong": { type: "string" }
        }
      }
    }
  },

  init: function() {
    ControlToExntend.prototype.init.apply(this, arguments);
    var oControl = this, oMyButton;
    oMyButton = new Button({ // Button required from "sap/m/Button"
      // ...,
      press: function (oEvent) {
        oControl.fireYourCustomEvent({
          passAlong: "Some dummy data to pass along"
        });
      }
    });
    this.setAggregation("_myButton", oMyButton);
  },

  // etc...
});

Hope this explains a bit.

OTHER TIPS

For custom events, you can wrap jquery events

So, use a general pattern like this can be followed:

events: {
    someEvent: {}
}

onBeforeRendering
    var domNode = this.getDomRef();
    $(domNode).unbind('someEvent')

onAfterRendering
    var self = this, domNode = this.getDomRef();
    $(domNode).bind('someEvent', function() {
        self.fireSomeEvent({
            customProp: customValue
        })
    });

A client of the control can do things like:

new CustomControl({
    someEvent: function( o ) {
        alert('customProp: ' + o.getParameter('customProp'));
    }
})

The recommendation / best practice is to register the event using such as jQuery.bind (and remove using jQuery.unbind() to avoid memory leak).

Find additional information (copied from Tim's comment): https://sapui5.netweaver.ondemand.com/sdk/#docs/guide/91f1b3856f4d1014b6dd926db0e91070.html

........
Good Luck

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top