Use ext js to build Ajax applications

Source: Internet
Author: User
Tags dateformat ruby on rails ibm developerworks

From IBM developerworks

Http://www.ibm.com/developerworks/cn/web/wa-aj-extjs? S_tact = 105agx52 & s_cmp = tec-csdn

 


A JavaScript Framework for Internet-rich Application Development


Document options

Print this page

Original ENGLISH

Level: Intermediate

John fronckowiak(John@idcc.net), President, IDC Consulting Inc.

July 21, 2008

Ext js is a powerful JavaScript library that simplifies Asynchronous JavaScript + XML (Ajax) development by using reusable objects and components. This article introduces ext JS, outlines the object-oriented JavaScript design concept behind it, and explains how to use the ext JS framework to develop user interface elements for Internet-rich applications.

Today, there are many web development frameworks, and it is difficult for developers to determine which frameworks are worth learning. Ext js is a Javascript development framework. This powerful JavaScript library simplifies Ajax development by using reusable objects and components. Web application developers should carefully consider using this tool. Ext js was originally written by Jack Slocum as a group of Yahoo! User Interface (Yui) Library Extension. However, with the release of Version 2.0, it has become the simplest and most powerful JavaScript library on the market.

Developerworks Ajax Resource Center
Ajax Resource CenterIs an all-in-one site that contains free tools, code, and information for developing Ajax applications.Active Ajax Community ForumHosted by Ajax expert Jack herrington, You can seek help from other developers here.

Ext js Overview

The purpose of the ext JS project is to expand the functions provided by the Yui library. A key aspect of Yui library is cross-browser support, which can also be found in ext Js. This support frees developers from considering the target browser when building Web applications.

Ext js provides excellent performance. This framework is fully object-oriented and scalable. Because ext JS is written in Javascript, you only need to download and install it to use the features of ext Js.

License Agreement

Before using a new framework, you must understand which license agreement terms the framework is based on. Ext js provides several license protocol options:

  • Open source code license:This applies to the terms of the open source lgpl 3.0 License. This is the most suitable license if you plan to use ext Js in another open source project or personal, educational, or non-profit project.
  • Commercial License:If you want to avoid certain restrictions on the development source code license when using ext Js in your project, or you must have a license for internal reasons, or you want to commercially support ext JS development, this is the most suitable license.ReferencesThe ext JS site is provided. This site provides detailed information about the commercial license.
  • Original equipment manufacturer (OEM)/reseller license:This license is most suitable if you plan to repackage ext JS or sell ext JS as a software development library.

Ext js browser support

All mainstream Web browsers support the ext JS framework, including:

  • Windows Internet Explorer 6 and later.
  • Mozilla Firefox 1.5 and later (PC and Macintosh ).
  • Apple Safari 2 and later.
  • Opera 9 and later versions (PC and MAC ).

Design Mode and ext JS

Developers should like ext JS's well-thought-out design and implementation. Its object-oriented design model reflects the relationship and interaction between objects. According to the designer, the design model used to develop ext JS is largely affectedHead first design patternsThis book (Eric Freeman and so on, referReferences. View the ext JS source code to find the creation mode (including Singleton design mode), structure mode (including flyweight design mode), and behavior mode (including Observer mode ).




Back to Top

Use ext js to build rich Internet applications

Ext js provides a large number of user interface elements, which are required to develop rich Internet applications (RIA. Ext js contains controls such as message boxes, combos, data networks, and toolbar. In addition, you can use the layout manager to specify how elements are displayed on the page. There are also other features used to operate forms and windows.

If other frameworks are used, the inclusion order of JavaScript files can be modified. However, ext JS usually followsListing 1That is included in the Web application (assuming that ext JS is installed in the LIB/EXT Directory on the Web server ):

Listing 1. Including the ext JS framework

<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 contains the entire Ext JS framework. You can reference the files in the above arrangement, or you can include only the files required by the elements used in the application.

Ext JS integration
You can use Ext JS with other popular server-side Web development frameworks, including PHP, Java ™ language, Microsoft® .NET, Ruby on Rails, and ColdFusion.

If you use the Ext JS framework in combination with other JavaScript libraries, please refer to the INCLUDE_ORDER.txt file in the installation root directory, which explains the order in which the libraries are included in the application.

User interface elements

The main body of the Ext JS framework is a large number of user interface elements. These elements include forms, dialog boxes, tabs, trees, and grids.

Form

Ext JS provides a set of tools for creating interactive forms. Figure 1 shows an example of a form. Listing 2 shows the relevant implementation.

Figure 1. Ext JS form example
 

Listing 2. Source code for Ext JS form example

                
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);
Dialogs and tabs

As shown in Figure 2, Ext JS supports the creation of modal dialog boxes for user input, and also supports the implementation of a tabbed user interface to make full use of screen space. The source code of the dialog box in Figure 2 is shown in Listing 3.

Figure 2. Ext JS modal dialogs and tabs

 

Listing 3. Source code of Ext JS modal dialog

                 
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);
Create a tree

As shown in Figure 3, Ext JS also provides a tree control, which provides users with a familiar view similar to the file system. The Ext JS tree control fully supports drag and drop functionality. The source code of the tree control shown in Figure 3 is shown in Listing 4.

Figure 3. Ext JS tree control
 

Listing 4. Source code of Ext JS tree control

                
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);
grid

Perhaps the most powerful Ext JS user interface element is the grid control. It can be used to display data from back-end data sources and other structured data, such as XML and arrays. As shown in Figure 4, Ext JS grid can achieve paging and column sorting. This example receives the latest topics from the ExtJS.com forum, highlighting the Ajax functionality of the Ext JS framework. The source code of the grid shown in Figure 4 is shown in Listing 5.

Figure 4. Ext JS grid control
 

Listing 5. Source code of Ext JS grid control

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

The Ext JS framework supports Ajax implementation. In general, a common feature of Ajax applications is that the application can asynchronously respond to user input, it will update part of the user interface without having to redisplay the entire Web page. Listing 6 shows a typical Ext JS Ajax implementation: when the button is clicked, the HTML text box and button elements send the data in the text box to the Web server.

Listing 6. Ajax implementation of Ext JS
                
<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" />
When the user clicks OK, an Ajax call is made using the Ext JS UpdateManage class, which is much simpler than the traditional Ajax HttpRequest call.

Ext JS integration with other web server frameworks

You can combine Ext JS with other commonly used server-side web development frameworks Used together, including PHP, Java language, Microsoft .NET, Ruby on Rails, and ColdFusion. For details on integration with these frameworks, see Resources.

Ext JS development tools

Ext JS development can be done in several popular integrated development environments (IDEs), including Eclipse, Aptana, and Komodo. For information about IDE support for Ext JS development, see Resources.

Conclusion

Web development frameworks often promise to simplify and accelerate application development, but many frameworks fail to achieve this goal. Ext JS fulfills its promise through an easy-to-use development model. The latest Ext JS version (2.0) shows that it is rapidly improving and can be the basis for RIA development.

This article is only a rough introduction to the main features of the Ext JS framework. The features of Ext JS are much more than that. Now, if you want to explore more deeply, start with the ExtJS.com Web site and interactive examples!

References

Learn

You can refer to the original English text of this article on the developerWorks global website.
Tutorial: Introduction to Ext: This tutorial can help you get started with Ext JS.
Ext JS documentation: Read the documentation of the 2.0 API.
Get more information about the commercial license of Ext JS.
"Design composite applications: design patterns": Learn more about design patterns (Jo Grant and Craig Wolpert, developerWorks, February 2008).
Head First Design Patterns: Read this book written by Eric Freeman et al. (O'Reilly, 2004), which influenced the design of Ext JS 2.0.
Master the Ajax series: Read this comprehensive series of developerWorks articles introducing Ajax.
Server-side frameworks for Ext JS: Learn more about the integration of Ext JS with frameworks such as Python, PHP, and Microsoft .NET.
Technology bookstore: Browse for books on these and other technical topics.
IBM technical events and webcasts: Keep an eye on developerWorks technical events and webcasts.
Get products and technologies

Ext JS version 2.0 framework: Download this framework.
IBM® trial software: Improve your next open source development project with IBM trial software, which can be downloaded or obtained on DVD.
discuss

Ext JS Forum: Participate in the Ext JS community.
Ext JS blogs: These blogs are the first place to find news and information about Ext JS.
developerWorks blog: Participate and join the developerWorks community.
About the author

John Fronckowiak is the president and founder of IDC Consulting Inc. and Western New York Web Design, LLC. He is also a clinical assistant professor of computer information systems at Mandal College. He has also written several books on programming, database design and development, and networking.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.