1. 程式人生 > >用 Ext JS 構建 Ajax 應用程式

用 Ext JS 構建 Ajax 應用程式

 

一種用於富因特網應用程式開發的 JavaScript 框架

developerWorks
文件選項
將印表機的版面設定成橫向列印模式

列印本頁

未顯示需要 JavaScript 的文件選項

英文原文

英文原文


級別: 中級

2008 年 7 月 21 日

Ext JS 是一種強大的 JavaScript™ 庫,它通過使用可重用的物件和部件簡化了 Asynchronous JavaScript + XML(Ajax)開發。本文介紹 Ext JS,概述它背後的面向物件 JavaScript 設計概念,解釋如何使用 Ext JS 框架開發富因特網應用程式的使用者介面元素。

當今有許許多多的 Web 開發框架,開發人員很難判斷哪些框架值得花時間去學習。Ext JS 是一種 JavaScript 開發框架,這種強大的 JavaScript 庫通過使用可重用的物件和部件簡化了 Ajax 開發,Web 應用程式開發人員應該認真考慮使用這個工具。Ext JS 最初是 Jack Slocum 編寫的一組 Yahoo! User Interface(YUI)Library 擴充套件。但是,隨著 2.0 版的釋出,它已經成為市場上最簡單最強大的 JavaScript 庫。

developerWorks Ajax 資源中心
Ajax 資源中心 是一站式站點,包含關於開發 Ajax 應用程式的免費工具、程式碼和資訊。活躍 Ajax 社群論壇 由 Ajax 專家 Jack Herrington 主持,您可以在這裡向其他開發人員尋求幫助。

Ext JS 專案最初的目的是擴充套件 YUI Library 提供的功能。YUI Library 的一個關鍵方面是跨瀏覽器支援,這也可以在 Ext JS 中找到。這種支援使開發人員在構建 Web 應用程式時不需要考慮目標瀏覽器。

Ext JS 提供出色的效能。這個框架是完全面向物件且可擴充套件的。因為 Ext JS 是用 JavaScript 編寫的,所以只需下載並安裝,就可以使用 Ext JS 的特性。

許可協議

在採用一個新框架之前,一定要了解框架基於哪種許可協議條款。Ext JS 提供幾個許可協議選項:

  • 開放原始碼許可證:這採用 Open Source LGPL 3.0 許可證的條款。如果打算在另一個開放原始碼專案或者個人、教育或非盈利專案中使用 Ext JS,這是最合適的許可證。
  • 商用許可證:如果希望在專案中使用 Ext JS 時避免開發原始碼許可證的某些限制,或者由於內部原因必須擁有許可證,或者希望在商業上支援 Ext JS 的開發,這是最合適的許可證。參考資料 中提供了 Ext JS 站點的連結,這個站點提供關於商用許可證的詳細資訊。
  • 原始裝置生產商(OEM)/轉售商許可證:如果您打算對 Ext JS 進行重新打包,或者作為軟體開發庫銷售 Ext JS,這種許可證是最合適的。

所有主流的 Web 瀏覽器都支援 Ext JS 框架,包括:

  • Windows® Internet Explorer® 6 及更高版本。
  • Mozilla Firefox 1.5 及更高版本(PC 和 Macintosh)。
  • Apple Safari 2 及更高版本。
  • Opera 9 及更高版本(PC 和 Mac)。

開發人員應該會喜歡 Ext JS 經過深思熟慮的設計和實現。它的面向物件設計模式反映了物件之間的關係和互動。據設計者說,開發 Ext JS 時使用的設計模式在很大程度上受到 Head First Design Patterns 這本書(Eric Freeman 等著,參見 參考資料)的影響。檢視 Ext JS 原始碼,就會發現建立模式(包括 singleton 設計模式)、結構模式(包括 flyweight 設計模式)和行為模式(包括 observer 模式)。





回頁首


Ext JS 提供大量使用者介面元素,這是開發富因特網應用程式(RIA)所必需的。Ext JS 包含訊息框、組合框、資料網格和工具欄等控制元件。另外,還可以通過佈局管理器指定元素在頁面上的顯示方式。還有用於操作表單和視窗的其他特性。

如果使用其他框架,JavaScript 檔案的包含次序是可以修改的。但是,Ext JS 通常按照 清單 1 那樣包含在 Web 應用程式中(假設 Ext JS 安裝在 Web 伺服器上的 lib/ext 目錄中):


清單 1. 包含 Ext JS 框架
                
<script type ="text/javascript" src="lib/ext/ext-base.js"></script>
<script type ="text/javascript" src="lib/ext/ext-all.js"></script>

ext-all.js 包含整個 Ext JS 框架。可以按照上面的排列引用檔案,也可以只包含應用程式中使用的元素所需的檔案。

Ext JS 的整合

可以把 Ext JS 與其他常用的伺服器端 Web 開發框架一起使用,包括 PHP、Java™ 語言、Microsoft® .NET、Ruby on Rails 和 ColdFusion。

如果結合使用 Ext JS 框架和其他 JavaScript 庫,請參考安裝根目錄中的 INCLUDE_ORDER.txt 檔案,它說明了在應用程式中包含庫的次序。

Ext JS 框架的主體是大量使用者介面元素。這些元素包括表單、對話方塊、選項卡、樹和網格。

表單

Ext JS 提供一組用來建立互動式表單的工具。圖 1 給出一個表單示例。清單 2 給出相關的實現。


圖 1. Ext JS 表單示例
Ext JS 表單示例

清單 2. Ext JS 表單示例的原始碼
                
var top = new Ext.FormPanel({
    labelAlign: 'top',
    frame:true,
    title: 'Multi Column, Nested Layouts and Anchoring',
    bodyStyle:'padding:5px 5px 0',
    width: 600,
    items: [{
        layout:'column',
        items:[{
            columnWidth:.5,
            layout: 'form',
            items: [{
                xtype:'textfield',
                fieldLabel: 'First Name',
                name: 'first',
                anchor:'95%'
            }, {
                xtype:'textfield',
                fieldLabel: 'Company',
                name: 'company',
                anchor:'95%'
            }]
        },{
            columnWidth:.5,
            layout: 'form',
            items: [{
            xtype:'textfield',
            fieldLabel: 'Last Name',
            name: 'last',
            anchor:'95%'
        },{
            xtype:'textfield',
            fieldLabel: 'Email',
            name: 'email',
            vtype:'email',
            anchor:'95%'
        }]
    }]
    },{
        xtype:'htmleditor',
        id:'bio',
        fieldLabel:'Biography',
        height:200,
        anchor:'98%'
    }],

        buttons: [{
        text: 'Save'
    },{
        text: 'Cancel'
    }]
});

    top.render(document.body);

圖 2 所示,Ext JS 支援建立用於使用者輸入的模態對話方塊,還支援實現選項卡式使用者介面,以便充分利用螢幕空間。圖 2 中對話方塊的原始碼見 清單 3


圖 2. Ext JS 模態對話方塊和選項卡
Ext JS 模態對話方塊和選項卡

清單 3. Ext JS 模態對話方塊的原始碼
                 
var LayoutExample = function(){
// everything in this space is private and only accessible in the HelloWorld block

// define some private variables
var dialog, showBtn;

var toggleTheme = function(){
    Ext.get(document.body, true).toggleClass('xtheme-gray');
};
// return a public interface
return {
    init : function(){
    showBtn = Ext.get('show-dialog-btn');
    // attach to click event
    showBtn.on('click', this.showDialog, this);       
},

showDialog : function(){
    if(!dialog){ // lazy initialize the dialog and only create it once
      dialog = new Ext.LayoutDialog("hello-dlg", { 
      modal:true,
      width:600,
      height:400,
      shadow:true,
      minWidth:300,
      minHeight:300,
      proxyDrag: true,
      west: {
        split:true,
        initialSize: 150,
        minSize: 100,
        maxSize: 250,
        titlebar: true,
        collapsible: true,
        animate: true
      },
      center: {
        autoScroll:true,
        tabPosition: 'top',
        closeOnTab: true,
        alwaysShowTabs: true
      }
  });
  dialog.addKeyListener(27, dialog.hide, dialog);
  dialog.addButton('Submit', dialog.hide, dialog);
  dialog.addButton('Close', dialog.hide, dialog);

  var layout = dialog.getLayout();
  layout.beginUpdate();
  layout.add('west', new Ext.ContentPanel('west', {title: 'West'}));
  layout.add('center', new Ext.ContentPanel('center', {title: 'The First Tab'}));
  // generate some other tabs
  layout.add('center', new Ext.ContentPanel(Ext.id(), {
    autoCreate:true, title: 'Another Tab', background:true}));
  layout.add('center', new Ext.ContentPanel(Ext.id(), {
    autoCreate:true, title: 'Third Tab', closable:true, background:true}));
  layout.endUpdate();
}
dialog.show(showBtn.dom);
}
};
}();

// using onDocumentReady instead of window.onload initializes the application
// when the DOM is ready, without waiting for images and other resources to load
Ext.EventManager.onDocumentReady(LayoutExample.init, LayoutExample, true);

建立樹

圖 3 所示,Ext JS 還提供樹控制元件,這種控制元件提供使用者熟悉的與檔案系統相似的檢視。Ext JS 樹控制元件完全支援拖放功能。圖 3 所示樹控制元件的原始碼見 清單 4


圖 3. Ext JS 樹控制元件
Ext JS 樹控制元件

清單 4. Ext JS 樹控制元件的原始碼
                
var TreeTest = function(){
// shorthand
  var Tree = Ext.tree;

  return {
    init : function(){
      // yui-ext tree
      var tree = new Tree.TreePanel({
          el:'tree',
          animate:true, 
          autoScroll:true,
          loader: new Tree.TreeLoader({dataUrl:'get-nodes.php'}),
          enableDD:true,
          containerScroll: true,
          dropConfig: {appendOnly:true}
      });

      // add a tree sorter in folder mode
      new Tree.TreeSorter(tree, {folderSort:true});

      // set the root node
      var root = new Tree.AsyncTreeNode({
        text: 'Ext JS', 
        draggable:false, // disable root node dragging
        id:'source'
      });
      tree.setRootNode(root);

      // render the tree
      tree.render();

      root.expand(false, /*no anim*/ false);

      //-------------------------------------------------------------

      // YUI tree            
      var tree2 = new Tree.TreePanel({
          el:'tree2',
          animate:true,
          autoScroll:true,
          loader: new Ext.tree.TreeLoader({
            dataUrl:'get-nodes.php',
            baseParams: {lib:'yui'} // custom http params
          }),
          containerScroll: true,
          enableDD:true,
          dropConfig: {appendOnly:true}
      });

      // add a tree sorter in folder mode
      new Tree.TreeSorter(tree2, {folderSort:true});

      // add the root node
      var root2 = new Tree.AsyncTreeNode({
          text: 'My Files', 
          draggable:false, 
          id:'yui'
      });
      tree2.setRootNode(root2);
      tree2.render();

      root2.expand(false, /*no anim*/ false);
    }
  };
}();

Ext.EventManager.onDocumentReady(TreeTest.init, TreeTest, true);     

網格

最強大的 Ext JS 使用者介面元素可能是網格控制元件。可以通過它顯示來自後端資料來源的資料和其他結構化資料,比如 XML 和陣列。如 圖 4 所示,Ext JS 網格可以實現分頁和列排序。這個示例接收來自 ExtJS.com 論壇的最新主題,強調了 Ext JS 框架的 Ajax 功能。圖 4 所示網格的原始碼見 清單 5


圖 4. Ext JS 網格控制元件
Ext JS 網格控制元件

清單 5. Ext JS 網格控制元件的原始碼
                
Ext.onReady(function(){

  // create the Data Store
  var store = new Ext.data.Store({
  // load using script tags for cross domain, if the data in on the same domain as
  // this page, an HttpProxy would be better
  proxy: new Ext.data.ScriptTagProxy({
    url: 'http://extjs.com/forum/topics-browse-remote.php'
  }),

  // create reader that reads the Topic records
  reader: new Ext.data.JsonReader({
    root: 'topics',
    totalProperty: 'totalCount',
    id: 'threadid',
    fields: [
      'title', 'forumtitle', 'forumid', 'author',
      {name: 'replycount', type: 'int'},
      {name: 'lastpost', mapping: 'lastpost', type: 'date', 
          dateFormat: 'timestamp'},
      'lastposter', 'excerpt'
    ]
  }),

  // turn on remote sorting
  remoteSort: true
});
store.setDefaultSort('lastpost', 'desc');

// pluggable renders
function renderTopic(value, p, record){
  return String.format(
  '<b><a href="http://extjs.com/forum/showthread.php?t={2}" 
      target="_blank">{0}</a></b>
      <a href="http://extjs.com/forum/forumdisplay.php?f={3}" 
      target="_blank">{1} Forum</a>',
    value, record.data.forumtitle, record.id, record.data.forumid);
}
function renderLast(value, p, r){
return String.format('{0}<br/>by {1}', value.dateFormat('M j, Y, g:i a'), 
                     r.data['lastposter']);
}

// the column model has information about grid columns
// dataIndex maps the column to the specific data field in
// the data store
var cm = new Ext.grid.ColumnModel([{
    id: 'topic',
    header: "Topic",
    dataIndex: 'title',
    width: 420,
    renderer: renderTopic
  },{
    header: "Author",
    dataIndex: 'author',
    width: 100,
    hidden: true
  },{
    header: "Replies",
    dataIndex: 'replycount',
    width: 70,
    align: 'right'
  },{
    id: 'last',
    header: "Last Post",
    dataIndex: 'lastpost',
    width: 150,
    renderer: renderLast
}]);

// by default columns are sortable
cm.defaultSortable = true;

var grid = new Ext.grid.GridPanel({
    el:'topic-grid',
    width:700,
    height:500,
    title:'ExtJS.com - Browse Forums',
    store: store,
    cm: cm,
    trackMouseOver:false,
    sm: new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn}),
    loadMask: true,
    viewConfig: {
      forceFit:true,
      enableRowBody:true,
      showPreview:true,
      getRowClass : function(record, rowIndex, p, store){
        if(this.showPreview){
        p.body = '<p>'+record.data.excerpt+'</p>';
          return 'x-grid3-row-expanded';
      }
      return 'x-grid3-row-collapsed';
    }
},
bbar: new Ext.PagingToolbar({
  pageSize: 25,
  store: store,
  displayInfo: true,
  displayMsg: 'Displaying topics {0} - {1} of {2}',
  emptyMsg: "No topics to display",
  items:[
    '-', {
    pressed: true,
    enableToggle:true,
    text: 'Show Preview',
    cls: 'x-btn-text-icon details',
    toggleHandler: toggleDetails
  }]
})
});

// render it
grid.render();

// trigger the data store load
store.load({params:{start:0, limit:25}});

function toggleDetails(btn, pressed) {
    var view = grid.getView();
    view.showPreview = pressed;
    view.refresh();
}
});

Ext JS 框架支援 Ajax 實現。通常,Ajax 應用程式的一個共有特性是應用程式可以非同步地響應使用者輸入,它會更新部分使用者介面,而不需要重新顯示整個 Web 頁面。清單 6 給出一個典型的 Ext JS Ajax 實現:當單擊按鈕時,HTML 文字框和按鈕元素把文字框中的資料傳送給 Web 伺服器。


清單 6. Ext JS 的 Ajax 實現
                
<script type =”text/javascript”>
Ext.onReady(function(){
  Ext.get('okButton').on('click', function(){
    var msg = Ext.get("msg");
    msg.load({
      url: [server url], // <-- replace with your url
        params: "name=" + Ext.get('name').dom.value,
        text: "Updating..."
    });
    msg.show();
  });
});
</script>
  
<div id="msg" style="visibility: hidden"></div>
Name: <input type="text" id="name" /><br />
<input type="button" id="okButton" value="OK" />

當用戶單擊 OK 時,使用 Ext JS UpdateManage 類發出 Ajax 呼叫,這比傳統的 Ajax HttpRequest 呼叫簡單多了。

可以把 Ext JS 與其他常用的伺服器端 Web 開發框架一起使用,包括 PHP、Java 語言、Microsoft .NET、Ruby on Rails 和 ColdFusion。關於與這些框架整合的詳細資訊,參見 參考資料

可以在幾種流行的整合開發環境(IDE)中進行 Ext JS 開發,包括 Eclipse、Aptana 和 Komodo。關於 IDE 對 Ext JS 開發的支援的資訊,參見 參考資料

結束語

Web 開發框架常常承諾簡化和加快應用程式開發,但是許多框架都沒有實現這個目標。Ext JS 通過一個易用的開發模型實現了它的承諾。最新的 Ext JS 版本(2.0)表明,它正在快速進步,可以成為 RIA 開發的基礎。

本文只是粗略地介紹 Ext JS 框架的主要特性,Ext JS 的特性遠不止這些。現在,如果要進行更深入的探索,請從 ExtJS.com Web 站點和 互動式示例 開始!



參考資料

學習

獲得產品和技術
  • IBM® 試用軟體:用 IBM 試用軟體改進您的下一個開放原始碼開發專案,這些軟體可以下載或者通過 DVD 獲得。


討論
  • Ext JS 論壇:參與 Ext JS 社群。

  • Ext JS blog:這些 blog 是尋找關於 Ext JS 的新聞和資訊的首選位置。



關於作者

John Fronckowiak

John Fronckowiak 是 IDC Consulting Inc. 和 Western New York Web Design, LLC 的總裁兼創辦人。他還是曼達爾學院計算機資訊系統的臨床助理教授。他還撰寫了幾本關於程式設計、資料庫設計和開發以及聯網的書。