SAPUI5 (06) - MVC 基礎(chǔ)

MVC 是一種架構(gòu)模式,SAPUI5 對 MVC 提供了良好的支持跋涣。

什么是 MVC?

MVC 是 Model阅懦、View和二、Controller 的簡稱,用于將程序的數(shù)據(jù)耳胎、界面展示和用戶交互分離惯吕,通過這種分離,可以簡化開發(fā)怕午,以及讓某部分變動的時候废登,不需要影響其他部分,從而降低耦合郁惜。

  • Model: 模型 - 代表應(yīng)用程序的數(shù)據(jù)
  • View: 通過界面展示應(yīng)用程序的數(shù)據(jù)和其它界面元素
  • Controller: 處理應(yīng)用程序的數(shù)據(jù)堡距,以及處理用戶的交互。

下面的圖示來自 SAPUI5 SDK兆蕉,清晰地說明了三個概念之間的關(guān)系:

圖片來自SAPUI5 SDK
  • Model 和 View 之間的關(guān)系:OpenUI5 有單向綁定或者雙向綁定兩種綁定模式羽戒,通過綁定,當(dāng) model 變更時虎韵, UI 自動更新半醉。
  • Controller 和 View 之間的關(guān)系:View 通知 Controller,或者 Controller使用 API 來修改 View劝术。
  • Controller 和 Model 的關(guān)系:Model 通知 Controller缩多,或者 Controller 修改 Model呆奕。

我們用一個實例來演示 MVC 。我們要實現(xiàn)的一個非常簡單的功能:在頁面上放一個 Button衬吆,當(dāng)用戶點擊的時候梁钾,顯示 "Hlello"。對逊抡,前面 Hello World 程序已經(jīng)實現(xiàn)過姆泻。我們先不用 MVC,將代碼寫在一個地方冒嫡,為了和之前代碼相比有點新東西拇勃,我們將 JavaScript 的 alert() 替換成sap.m.MessageBox.information(),OpenUI5 風(fēng)格的對話框孝凌。先介紹一下 sap.m.MessageBox:

sap.m.MessageBox 對象

sap.m.MessageBox 是 OpenUI5 提供的對話框方咆,可以顯示信息、警告蟀架、錯誤等等瓣赂。MessageBox 類是靜態(tài)類,在使用之前必須執(zhí)行

jQuery.sap.require("sap.m.MessageBox");

語句片拍。OpenUI5 帶有 jQuery 包煌集,jQuery.sap.require(vModuleName) 方法的作用是加載指定的模塊并且執(zhí)行,這樣 MessageBox才被加載捌省, show() 方法才能運行苫纤。

sap.m.MessageBox 有如下方法:

  • alert: 對話框顯示一個消息,有一個 OK 按鈕(注意在中文環(huán)境中 OK 被翻譯為確定)纲缓,沒有圖標(biāo) (icon)
  • confirm: 確認(rèn)對話框卷拘,詢問是否確認(rèn),有一個 OK 按鈕和 Cancel 按鈕色徘,一個問號的圖標(biāo)
  • information:消息對話框恭金,帶有 INFO 圖標(biāo)和 OK 按鈕;
  • error:顯示錯誤對話框褂策,帶有錯誤圖標(biāo)和關(guān)閉按鈕 (Displays an error dialog with the given message, an ERROR icon, a CLOSE button)
  • success:顯示成功對話框横腿,帶有 SUCCESS 圖標(biāo)和 OK 按鈕
  • warning:顯示警告消息,帶有 WARNING 圖標(biāo)和 OK 按鈕
  • show:顯示一個對話框斤寂,類型為sap.m.DialogType.Message耿焊,圖標(biāo)和按鈕由開發(fā)人員自行定義,提供更大的靈活性

語法基本相同:

sap.m.MessageBox.some_method(vMessage, mOptions?)

不使用 MVC 實現(xiàn)功能

OK遍搞,我們先把代碼都寫在 index.html 中:

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>

        <script src="resources/sap-ui-core.js"
                id="sap-ui-bootstrap"
                data-sap-ui-libs="sap.m"
                data-sap-ui-theme="sap_bluecrystal">
        </script>
        
        <!-- Application area -->
        <script>
            function display() {
                var oButton = new sap.m.Button({text: "Click me."});
                
                oButton.attachPress(function() {
                    jQuery.sap.require("sap.m.MessageBox");
                    sap.m.MessageBox.information("Hello SAPUI5!", {                     
                        title: "SAPUI5 button test"
                    });
                });
                
                oButton.placeAt("content");
            }
            
            sap.ui.getCore().attachInit(display);
        </script>

    </head>
    <body class="sapUiBody" role="application">
        <div id="content"></div>
    </body>
</html>

使用 MVC 實現(xiàn)

本示例只有點擊 Button罗侯,并沒有數(shù)據(jù),所以只涉及 view 和 controller溪猿。首先我們介紹一下 OpenUI5 的 View 有哪些類型钩杰。

SAPUI5 有哪些類型的 View纫塌?

SAPUI5 提供了JSView, XMLView, JSONViewHTMLView 等幾種類型。SAPUI5 的示例代碼主要采用 XMLView讲弄,這個也是現(xiàn)代開發(fā)語言的趨勢措左。而對開發(fā)人員來說,JSView 也可能感覺比較舒適避除,所以建議重點掌握這兩個類型就可以了怎披,并且學(xué)會在兩種風(fēng)格的代碼之間進行翻譯。

Eclipse 中如何創(chuàng)建 View?

當(dāng)在 Eclipse 中新建一個SAPUI5 Application Project 類型的項目時瓶摆,Eclipse 會提示是否創(chuàng)建 initial view凉逛,如果勾選,Eclipse 會創(chuàng)建 MVC 分離的代碼框架群井。另外状飞,開發(fā)人員也隨時可以創(chuàng)建 View。我們先來看第一種方式:

新建一個 SAPUI5 Application Project蝌借,project name 為zsapui5_butto_mvc昔瞧,勾選 Create an Initial View:

點擊 Next指蚁,選擇 JavaScript View菩佑,把 View 命名為 master:

點擊 Finish,代碼框架創(chuàng)建完成凝化。來探索一下代碼:

代碼說明

index.html 文件

首先還是 index.html (在 WebContent 文件夾下)稍坯,我們注意到,Application area 的代碼發(fā)生了變化搓劫,這個是另一個常用的模式瞧哟。

<script>
        sap.ui.localResources("zsapui5_button_mvc");
        var app = new sap.m.App({initialPage:"idmaster1"});
        var page = sap.ui.view({
            id:"idmaster1", 
            viewName:"zsapui5_button_mvc.master", 
            type:sap.ui.core.mvc.ViewType.JS});
        app.addPage(page);
        app.placeAt("content");
</script
  • sap.ui.localResources("zsapui5_button_mvc"); : 作用是將當(dāng)前目錄下的 zsapui5_button_mvc 文件夾注冊為當(dāng)前文件夾,程序會在這個文件夾下查找 view 的代碼和 controller 的代碼枪向。我們剛才把 view 命名為 master勤揩,所以 OpenUI5 在 ./zsapui5_button_mvc 文件夾下查找master.view.js,把這個文件作為存放 view 的代碼文件秘蛔。同理陨亡,在這個文件夾下查找 master.controller.js,把這個文件作為存放 controller 的代碼文件深员。后面我們會專門介紹文件位置如何處理的問題负蠕,暫且不表。

  • new sap.m.App: 創(chuàng)建一個 sap.m.App 對象倦畅,sap.m.App 對象是
    SAP 移動 app 的根元素 (root element)遮糖,它提供導(dǎo)航的功能,并且將一些
    header 標(biāo)簽加到 HTML 頁叠赐,這些 header 標(biāo)簽對移動 app 有某些作用欲账。

  • sap.ui.view: 定義一個 view屡江,設(shè)定 id, view name 和 type,這個 view
    賦值給 page 并添加到 app 中赛不。app 的初始頁需要用到 view 的 id盼理,而view 的 name 則和上面 sap.ui.localResources("zsapui5_button_mvc");
    語句一起,確定了代碼文件的位置俄删。

  • app.placeAt("content"): app 放在 DIV 中宏怔,UI 就可以顯示。

View 文件

View 文件為 WebContent/zsapui5_button_mvc/master.view.js畴椰。代碼如下:

sap.ui.jsview("zsapui5_button_mvc.master", {

    /** Specifies the Controller belonging to this View. 
    * In the case that it is not implemented, or that "null" is returned, this View does not have a Controller.
    * @memberOf zsapui5_button_mvc.master
    */ 
    getControllerName : function() {
        return "zsapui5_button_mvc.master";
    },

    /** Is initially called once after the Controller has been instantiated. It is the place where the UI is constructed. 
    * Since the Controller is given to this method, its event handlers can be attached right away. 
    * @memberOf zsapui5_button_mvc.master
    */ 
    createContent : function(oController) {
        return new sap.m.Page({
            title: "Title",
            content: [
            
            ]
        });
    }
});

里面有兩個函數(shù)臊诊,getControllerName 函數(shù)用于返回 controller name,createContent 函數(shù)用于返回頁面上要顯示的元素斜脂,比如我們現(xiàn)在要返回的是一個 Button抓艳,我們將這個函數(shù)改寫為:

    createContent : function(oController) {
        var oButton = new sap.m.Button({
            text: "Click me",
            press: oController.onButtonPressed
        });
        
        return oButton;
    }

點擊的時候,調(diào)用 controller 中的 onButtonPressed 方法帚戳。

控制器代碼文件

控制器代碼文件為 WebContent/zsapui5_button_mvc/master.controller.js玷或。在Eclipse 中創(chuàng)建的 Controller, 起始代碼如下:

sap.ui.controller("zsapui5_button_mvc.master", {

/**
* Called when a controller is instantiated and its View controls (if available) are already created.
* Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
* @memberOf zsapui5_button_mvc.master
*/
//  onInit: function() {
//
//  },

/**
* Similar to onAfterRendering, but this hook is invoked before the controller's View is re-rendered
* (NOT before the first rendering! onInit() is used for that one!).
* @memberOf zsapui5_button_mvc.master
*/
//  onBeforeRendering: function() {
//
//  },

/**
* Called when the View has been rendered (so its HTML is part of the document). Post-rendering manipulations of the HTML could be done here.
* This hook is the same one that SAPUI5 controls get after being rendered.
* @memberOf zsapui5_button_mvc.master
*/
//  onAfterRendering: function() {
//
//  },

/**
* Called when the Controller is destroyed. Use this one to free resources and finalize activities.
* @memberOf zsapui5_button_mvc.master
*/
//  onExit: function() {
//
//  }

});

我們看到,這些函數(shù)都被注釋掉了片任,它們是 controller 生命周期中很重要的方法偏友,我們后面再介紹,目前我們只需要加上 onButtonPressed() 方法对供。我把它寫在最前面位他,后面的代碼保持不動产场。當(dāng)然鹅髓,你也可以刪除。

sap.ui.controller("zsapui5_button_mvc.master", {
    onButtonPressed: function() {
        jQuery.sap.require("sap.m.MessageBox");
        sap.m.MessageBox.information("Hello from MVC.", {
            title: "SAPUI5 MVC test"
        });
    }

/**
* Called when a controller is instantiated and its View controls (if available) are already created.
* Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
* @memberOf zsapui5_button_mvc.master
*/
//  onInit: function() {
//
//  },

/**
* Similar to onAfterRendering, but this hook is invoked before the controller's View is re-rendered
* (NOT before the first rendering! onInit() is used for that one!).
* @memberOf zsapui5_button_mvc.master
*/
//  onBeforeRendering: function() {
//
//  },

/**
* Called when the View has been rendered (so its HTML is part of the document). Post-rendering manipulations of the HTML could be done here.
* This hook is the same one that SAPUI5 controls get after being rendered.
* @memberOf zsapui5_button_mvc.master
*/
//  onAfterRendering: function() {
//
//  },

/**
* Called when the Controller is destroyed. Use this one to free resources and finalize activities.
* @memberOf zsapui5_button_mvc.master
*/
//  onExit: function() {
//
//  }

});

這樣京景,就用 MVC 方式實現(xiàn)了和前面一樣的功能窿冯。需要說明的時,Eclipse 的 Controller 代碼是一種老式的代碼确徙。因為 SAP 已經(jīng)停止對 Eclipse 開發(fā)插件的支持醒串,所以也不會再更新。后面我們經(jīng)常用的是 sap.ui.define 方法定義的 controller 代碼米愿。后續(xù)介紹厦凤。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市育苟,隨后出現(xiàn)的幾起案子较鼓,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件博烂,死亡現(xiàn)場離奇詭異香椎,居然都是意外死亡,警方通過查閱死者的電腦和手機禽篱,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進店門畜伐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人躺率,你說我怎么就攤上這事玛界。” “怎么了悼吱?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵慎框,是天一觀的道長。 經(jīng)常有香客問我后添,道長笨枯,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任遇西,我火速辦了婚禮馅精,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘粱檀。我一直安慰自己洲敢,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布梧税。 她就那樣靜靜地躺著沦疾,像睡著了一般称近。 火紅的嫁衣襯著肌膚如雪第队。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天刨秆,我揣著相機與錄音凳谦,去河邊找鬼。 笑死衡未,一個胖子當(dāng)著我的面吹牛尸执,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播缓醋,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼如失,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了送粱?” 一聲冷哼從身側(cè)響起褪贵,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后脆丁,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體世舰,經(jīng)...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年槽卫,在試婚紗的時候發(fā)現(xiàn)自己被綠了跟压。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,488評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡歼培,死狀恐怖震蒋,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情躲庄,我是刑警寧澤喷好,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站读跷,受9級特大地震影響梗搅,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜效览,卻給世界環(huán)境...
    茶點故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一无切、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧丐枉,春花似錦哆键、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至弯院,卻和暖如春辱士,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背听绳。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工颂碘, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人椅挣。 一個月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓头岔,卻偏偏與公主長得像,于是被迫代替她去往敵國和親鼠证。 傳聞我的和親對象是個殘疾皇子峡竣,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,500評論 2 359

推薦閱讀更多精彩內(nèi)容