How to add event listener to HTML canvas element added to XML view in UI5?

Viewed 362
  1. This is my XML fragment. I added this fragment in my main view. I know the fragment doesn't have its own controller, it uses main view controller. Here I added one event listener to HTML <canvas> element and tried to handle it in main controller. But this event is not triggering. How to handle this event?

  2. Can I write my own logic for this event using JavaScript or do I have to use a controller for this?

    <VBox xmlns="sap.m" xmlns:html="http://www.w3.org/1999/xhtml" class="sapUiSmallMargin">
      <!-- ... -->
      <html:canvas id="AnnCanvas"
        width="500px"
        height="500px"
        onclick="canvasCalled()"
        style="border:1px solid red; background-color:green; position:absolute;"></html:canvas>
      <!-- ... -->
    </VBox>
    

Like this, I added event for canvas in my controller file:

canvasCalled: function () {
  MessageToast.show("canvas Called");
},
1 Answers

Dom-Events bubble, there is no need to attache it directly. jQuery has a good API to utilise this feature.

The off call prevents double attachments in case onAfterRendering is called again because off data rebinding etc.

sap.ui.controller("view1.initial", {
  onInit: function(){
    this._sCanvasWrapperID =  '#' + this.getView().byId("canvasWrapper").getId();
  },
  destroy: function(){
    $(this._sCanvasWrapperID).off();
  },
  onAfterRendering: function() {
    $(this._sCanvasWrapperID).off().on("click contextmenu","canvas", this.onCanvasEvent.bind(this));
    // instead of this._sCanvasWrapperID, you can also use 'canvas' and let the event bubble till dom-root. 
    // $('canvas').off().on("click contextmenu", this.onCanvasEvent.bind(this));
  },
  onCanvasEvent: function(oJqueryEvent){
     event.preventDefault();
     console.log(`${this.getView().getId()} received event: ${event.type}`);
  }

});

sap.ui.xmlview("main", {
  viewContent: jQuery("#view1").html()
}).placeAt("uiArea");
<script id="sap-ui-bootstrap" src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js" data-sap-ui-theme="sap_bluecrystal" data-sap-ui-xx-bindingSyntax="complex" data-sap-ui-compatVersion="edge" data-sap-ui-libs="sap.m"></script>

<div id="uiArea"></div>

<script id="view1" type="ui5/xmlview">
  <mvc:View controllerName="view1.initial" xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns:html="http://www.w3.org/1999/xhtml">
    <VBox id="canvasWrapper" class="sapUiSmallMargin">
      <!-- ... -->
      <html:canvas width="500px" height="500px" style="border:1px solid red; background-color:green; position:absolute;"></html:canvas>
      <!-- ... -->
    </VBox>
  </mvc:View>
</script>

Related