티스토리 뷰

SAPUI5에 EventBus를 찾아보면 이렇게 나옵니다.

It is recommended to use the EventBus only when there is no other option to communicate between different instances, e.g. native UI5 events.(어쩔 수 없을 경우에만 사용)

여러분이 EventBus까지 알아본거면 이 방법을 사용할 수 밖에 없는 경우라고 생각합니다. 간단하게 설명하면 EventBus는 주로 다른 View 사이에서 Event를 캐치해야 할 때 사용됩니다. 사용하는 방법은 간단합니다.


Event를 발생시키는 View

1
2
3
4
<mvc:View controllerName="com.edu.orderFirst.controller.View2" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m">
    <Text text="View2 Area" />
    <Button text="View2" press=".onPress" />
</mvc:View>
cs

Event를 발생시키는 Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
sap.ui.define([
    "sap/ui/core/mvc/Controller",
    'sap/ui/export/library',
    'sap/ui/export/Spreadsheet'
], function (Controller, exportLibrary, Spreadsheet) {
    "use strict";
    
    var EdmType = exportLibrary.EdmType;
 
    return Controller.extend("com.edu.orderFirst.controller.View2", {
        onInit: function () {
        },
        
        onPress : function (sChannelId, sEventId, sData) {
            sap.ui.getCore().getEventBus().publish(
                "SomeChannel",
                "SomeEvent",
                {text: "An event has occurred in View2"}
            );
        }
    });
});
cs

Event를 발생시키는 곳은 별로 특별할 게 없습니다. 일반적으로 Event를 발생시키는 것처럼 View와 Cotnroller를 세팅해주고 이벤트에 바인딩된 함수에서 위의 코드처럼 세팅을 해줍니다. 첫번째 parameter는 Channel Id, 두번째 parameter는 Event Id, 세번째 parameter는 넘겨줄  데이터를 객체로 세팅하시면 됩니다. Channel Id와 Event Id는 유니크하게만 지정하면 됩니다.("sap.ui"는 Channel Id로 이미 예약되었기 때문에 사용할 수 없습니다)


Event를 받는 Controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/m/MessageBox"
], function (Controller, MessageBox) {
    "use strict";
 
    return Controller.extend("com.edu.orderFirst.controller.View3", {
        onInit: function () {
            sap.ui.getCore().getEventBus().subscribe(
                "SomeChannel",
                "SomeEvent",
                this.onPress2  ,
                this
            );
        },
        onPress2 : function (sChannelId, sEventId, sData) {
            MessageBox.success(sData.text + ". But The event is triggered in View3 ");
            //console.log(sData.text);
        }
    });
});
cs

Event를 받는 부분에는 미리 subscribe을 설정해 주셔야 합니다. Event가 발생시키는 곳에 설정하셨던(publish했던 곳) Channel Id와 Event Id를 똑같이 설정해 줍니다.(첫번째, 두번째 parameter) 세번째 parameter로 실행시킬 함수를 지정해 줍니다. 이 때 주의하셔야 할 것은 직접함수(parameter 자리에 function() {} 으로 넣는 방법)를 넣지 않고 위에 처럼 외부의 함수를 정의하고 호출하는 경우 함수 이름 뒤에 ()를 붙이지 않습니다. 네번째 paramter로 this를 설정해 주시면 됩니다.

실행화면


처음에는 헷갈릴 수 있는데 막상 해보면 간단하게 처리됩니다. SCP webide에 작성한 예제 파일을 첨부했습니다.

orderFirst.zip




참고 URL

https://openui5.hana.ondemand.com/api/sap.ui.core.EventBus#constructor

https://blogs.sap.com/2015/10/25/openui5-sapui5-communication-between-controllers-using-publish-and-subscribe-from-eventbus/


댓글