iT邦幫忙

DAY 3
3

extjs 4 + grails 開發實戰系列 第 3

extjs 4 mixins(混和) 特性說明

  • 分享至 

  • twitterImage
  •  

在有限的時間中,要學會一個前端框架不容易,也沒有一個框架是萬能的,但總要有個開始,筆者在進幾年一直在 extjs 的世界打滾,已有三四年的經驗,最近負責的專案除了使用 extjs,後端使用 grails,發現好處多多,就開發過程中的經驗與大家分享,從實際的例子還有兩個框架遇到得整合問題一一介紹
extjs4 中的 mixsins 是 extjs4 的新特性,在筆者之前寫過的文章中 extjs 4 系列 1/5:新特性與基本概念mixins (混合複數classes) 章節,有做過簡單介紹,讀者可以參考相關說明,了解 mixsins 的特性,官方 API 可參考連結:mixins API,在 extjs 中屬於 Ext.Class 的函式,也就等於所有不管 mvc 或是元件,都可以使用 mixins 的特性。

接著,想要知道 mixins 在不同狀況下的處理方式可參考 Ext JS 4 First Look 中文翻譯 mixins 章節,在使用上就必須要注意什麼情況下函式或屬性在捨麼情況下會被保留,什麼會被覆蓋。

舉個例子,假設我們有兩個 controller 分別如下:

共用元件之 controller:

Ext.define('foodprint.controller.StdController', {
    extend: 'Ext.app.Controller',
 
    views: [
        'StdEditorToolbar'
    ],
 
    refs: [
        {
            ref: 'stdEditorToolbar',
            selector: 'stdeditortoolbar'
        }
    ],
 
    initial: function(tbar) {
		...
    },
 
    onCreateBtnClick: function(btn) {
     ... 
    }
 
});

另一個別功能之 controller:

Ext.define('foodprint.controller.AController', {
    extend: 'Ext.app.Controller',

    mixins: {
        StdEditorToolbarCtrl: 'foodprint.controller.StdController'
    },

    views: [
        'BatchEditor'
    ],

    refs: [
        {
            ref: 'batchGrid',
            selector: 'batchgrid'
        }
    ],

    init: function(application) {
		...
    },

    readBatch: function(obj, record, item, index, e, eOpts) {
		...
    },


});

在上述的使用情境中,StdController 中的 refs 將會失效,保留 AController 中的 refs,因此在這樣狀況下,若要在 AController 也要能夠有 StdController 中 refs 定義的元件,勢必要在 AController 再次定義一次 StdController 的 refs。

另一種使用情境:假設被 mixins 的類別跟基礎類別有同名的函式,但是我們希望兩個個別實作同名函式**都可以被執行**可以參考 mixins API的範例:

Ext.define('CanSing', {
     sing: function() {
         alert("I'm on the highway to hell...")
     }
});

Ext.define('Musician', {
     mixins: {
         canSing: 'CanSing'
     },

     sing: function() {
         // delegate singing operation to mixin
         this.mixins.canSing.sing.call(this);
     }
})

希望透過本篇可以讓讀者了解 mixins 的特性,進而有效的重覆利用函式,減少不必要的重覆程式碼。

Ext JS 教學內容由思創軟體提供,共同作者 @lyhcode@smlsun 目前在校園及企業從事 JavaScript(含 Node.js, Ext JS)與 Java(含 Groovy, Grails, Gradle) 教育訓練及顧問工作。


上一篇
使用 sencha architect 開發 extjs 應用程式注意事項
下一篇
extjs 精簡程式碼案例分享
系列文
extjs 4 + grails 開發實戰9
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

我要留言

立即登入留言