Skip to content Skip to sidebar Skip to footer

How To Handle Event For Html Tags Defined Within Xml View?

I am trying to combine UI5 XMLView and standard HTML elements. In XML view, we can use press='.onSomething' attribute and onSomething: function(){} in the controller. But how to ha

Solution 1:

The HTML elements are copied by the XMLView into the page on rendering of the View. As they are not UI5 controls but HTML DOM elements, the events and properties will not be processed. So the code in your onclick events will be copied untouched to the output page.

When the user clicks on such a link, the code will be executed in the global window context. There is no easy way to find the UI5 View instance that has rendered the link and its Controller instance where your want to call a method.

The easiest way to attach HTML events to a controller method would be to give the HTML elements an id and bind the events in your controller's onAfterRendering hook:

<!-- In the View definition --><html:axmlns:html="http://www.w3.org/1999/xhtml"id="myLink"href="#">My Link</html:a>
{ // ControlleronBeforeRendering: function() {
    // Remove the exiting event handler to prevent double-registration next timeif (this._abortController && typeofthis._abortController.abort === "function") {
      this._abortController.abort(); // deregisters the handler
    }
  },

  onAfterRendering: function() {
    this._abortController = newAbortController();
    const htmlElement = document.getElementById(this.createId("myLink"));
    htmlElement.addEventListener("click", this.onClick.bind(this), {
      signal: this._abortController.signal// making the handler removable
    });
  },

  onClick: function() {
    alert("Clicked!");
  },
}

Example on JSBin.


About the AbortController, see "Add an abortable listener" from MDN.

Post a Comment for "How To Handle Event For Html Tags Defined Within Xml View?"