如何将事件侦听器添加到ui5中添加到xml视图的html画布元素?

bq9c1y66  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(337)

这是我的xml片段。我在我的主视图中添加了这个片段。我知道片段没有自己的控制器,它使用主视图控制器。在这里,我向html添加了一个事件侦听器 <canvas> 元素,并尝试在主控制器中处理它。但这一事件并没有触发。如何处理此事件?
我可以使用javascript为这个事件编写自己的逻辑吗?或者我必须为此使用控制器吗?

<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>

像这样,我在控制器文件中添加了画布事件:

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

koaltpgm1#

dom事件气泡,不需要直接附加它。jquery有一个很好的api来利用这个特性。
这个 off 调用可防止出现双重附件的情况 onAfterRendering 由于关闭数据重新绑定等原因再次调用。

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>

相关问题