论坛首页 Web前端技术论坛

Extjs Introduction

浏览 18301 次
精华帖 (0) :: 良好帖 (1) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-07-08  
from http://hideto.beyondrails.com/blogs/14
1,Overview
What is Ext all about?
引用

Ext is a client-side, JavaScript framework for building web applications. In early 2006, Jack Slocum began working on a set of extension utilities for the Yahoo! User Interface (YUI) library. These extensions were quickly organized into an independent library of code and distributed under the name "yui-ext." In the fall of 2006, Jack released version .33 of yui-ext, which turned out to be the final version of the code under that name (and under the open source BSD license). By the end of the year, the library had gained so much in popularity that the name was changed simply to Ext, a reflection of its maturity and independence as a layout:'fit',framework. A company was formed in early 2007, and Ext is now dual-licensed under the GPL and a commercial license. The library officially hit version 1.0 on April 1, 2007.

2,Architecture

1) Observable
Class: Ext.util.Observable
Subclasses: Component, Resizable, SplitBar, Updater, NativeObservable, Connection, DataProxy, Node, Store, Tree, BasicForm, AbstractSelectionModel, ColumnModel, GridView, PropertyStore, Menu, DefaultSelectionModel, MultiSelectionModel, TreeLoader, ClickRepeater, MixedCollection
Extends: Object
Abstract base class that provides a common interface for publishing events. Subclasses are expected to to have a property "events" with all the events defined.
Employee = function(name){
    this.name = name;
    this.addEvents({
        "fired" : true,
        "quit" : true
    });
}
Ext.extend(Employee, Ext.util.Observable);

2) Component
Class: Ext.Component
Subclasses: BoxComponent, Button, ColorPalette, DatePicker, Editor, BaseItem
Extends: Observable
Base class for all Ext components. All subclasses of Component can automatically participate in the standard Ext component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show and enable/disable behavior. Component allows any subclass to be lazy-rendered into any Ext.Container and to be automatically registered with the Ext.ComponentMgr so that it can be referenced at any time via Ext.getCmp. All visual widgets that require rendering into a layout should subclass Component (or Ext.BoxComponent if managed box model handling is required).
Every component has a specific xtype, which is its Ext-specific type name, along with methods for checking the xtype like getXType and isXType. This is the list of all valid xtypes:
xtype            Class
-------------    ------------------
box              Ext.BoxComponent
button           Ext.Button
colorpalette     Ext.ColorPalette
component        Ext.Component
container        Ext.Container
cycle            Ext.CycleButton
dataview         Ext.DataView
datepicker       Ext.DatePicker
editor           Ext.Editor
editorgrid       Ext.grid.EditorGridPanel
grid             Ext.grid.GridPanel
paging           Ext.PagingToolbar
panel            Ext.Panel
progress         Ext.ProgressBar
propertygrid     Ext.grid.PropertyGrid
slider           Ext.Slider
splitbutton      Ext.SplitButton
statusbar        Ext.StatusBar
tabpanel         Ext.TabPanel
treepanel        Ext.tree.TreePanel
viewport         Ext.Viewport
window           Ext.Window

Toolbar components
---------------------------------------
toolbar          Ext.Toolbar
tbbutton         Ext.Toolbar.Button
tbfill           Ext.Toolbar.Fill
tbitem           Ext.Toolbar.Item
tbseparator      Ext.Toolbar.Separator
tbspacer         Ext.Toolbar.Spacer
tbsplit          Ext.Toolbar.SplitButton
tbtext           Ext.Toolbar.TextItem

Form components
---------------------------------------
form             Ext.FormPanel
checkbox         Ext.form.Checkbox
combo            Ext.form.ComboBox
datefield        Ext.form.DateField
field            Ext.form.Field
fieldset         Ext.form.FieldSet
hidden           Ext.form.Hidden
htmleditor       Ext.form.HtmlEditor
label            Ext.form.Label
numberfield      Ext.form.NumberField
radio            Ext.form.Radio
textarea         Ext.form.TextArea
textfield        Ext.form.TextField
timefield        Ext.form.TimeField
trigger          Ext.form.TriggerField

3) BoxComponent
Class: Ext.BoxComponent
Subclasses: Container, DataView, ProgressBar, Slider, Toolbar, Field, Label
Extends: Component
Base class for any visual Ext.Component that uses a box container. BoxComponent provides automatic box model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All container classes should subclass BoxComponent so that they will work consistently when nested within other Ext layout containers.
All box model widget classes extend BoxComponent, other widget classes extend Component directly, such as Button, ColorPalette, DatePicker, Editor, Separator, TextItem ...
4) Container
Class: Ext.Container
Subclasses: Panel, Viewport
Extends: BoxComponent
Base class for any Ext.BoxComponent that can contain other components. Containers handle the basic behavior of containing items, namely adding, inserting and removing them. The specific layout logic required to visually render contained items is delegated to any one of the different layout classes available. This class is intended to be extended and should generally not need to be created directly via the new keyword.
5) Panel
Class: Ext.Panel
Subclasses: TabPanel, Tip, Window, FieldSet, FormPanel, GridPanel, TreePanel
Extends: Container
Panel is a container that has specific functionality and structural components that make it the perfect building block for application-oriented user interfaces. The Panel contains bottom and top toolbars, along with separate header, footer and body sections. It also provides built-in expandable and collapsible behavior, along with a variety of prebuilt tool buttons that can be wired up to provide other customized behavior. Panels can be easily dropped into any Container or layout, and the layout and rendering pipeline is completely managed by the framework.
6) Viewport
Class: Ext.Viewport
Extends: Container
A specialized container representing the viewable application area (the browser viewport).
The Viewport renders itself to the document body, and automatically sizes itself to the size of the browser viewport and manages window resizing. There may only be one Viewport created in a page. Inner layouts are available by virtue of the fact that all Panels added to the Viewport, either through its items, or through the items, or the add method of any of its child Panels may themselves have a layout.
The Viewport does not provide scrolling, so child Panels within the Viewport should provide for scrolling if needed using the autoScroll config.
7) Window
Class: Ext.Window
Extends: Panel
A specialized panel intended for use as an application window. Windows are floated and draggable by default, and also provide specific behavior like the ability to maximize and restore (with an event for minimizing, since the minimize behavior is application-specific). Windows can also be linked to a Ext.WindowGroup or managed by the Ext.WindowManager to provide grouping, activation, to front/back and other application-specific behavior.
8) ContainerLayout
Class: Ext.layout.ContainerLayout
Subclasses: AnchorLayout, BorderLayout, ColumnLayout, FitLayout, TableLayout
Extends: Object
Every layout is composed of one or more Ext.Container elements internally, and ContainerLayout provides the basic foundation for all other layout classes in Ext. It is a non-visual class that simply provides the base logic required for a Container to function as a layout. This class is intended to be extended and should generally not need to be created directly via the new keyword.

3,DomQuery/DomHelper
Class: Ext.DomQuery
Extends: Object
Provides high performance selector/xpath processing by compiling queries into reusable functions. New pseudo classes and matchers can be plugged. It works on HTML and XML documents (if a content node is passed in).
DomQuery supports most of the CSS3 selectors spec, along with some custom selectors and basic XPath.
All selectors, attribute filters and pseudos below can be combined infinitely in any order. For example "div.foo:nth-child(odd)[@foo=bar].bar:first" would be a perfectly valid selector. Node filters are processed in the order in which they appear, which allows you to optimize your queries for your document structure.

1) Element Selectors
* any element
E an element with the tag E
E F All descendent elements of E that have the tag F
E > F or E/F all direct children elements of E that have the tag F
E + F all elements with the tag F that are immediately preceded by an element with the tag E
E ~ F all elements with the tag F that are preceded by a sibling element with the tag E

2) Attribute Selectors
The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.
E[foo] has an attribute "foo"
E[foo=bar] has an attribute "foo" that equals "bar"
E[foo^=bar] has an attribute "foo" that starts with "bar"
E[foo$=bar] has an attribute "foo" that ends with "bar"
E[foo*=bar] has an attribute "foo" that contains the substring "bar"
E[foo%=2] has an attribute "foo" that is evenly divisible by 2
E[foo!=bar] has an attribute "foo" that does not equal "bar"

3) Pseudo Classes
E:first-child E is the first child of its parent
E:last-child E is the last child of its parent
E:nth-child(n) E is the nth child of its parent (1 based as per the spec)
E:nth-child(odd) E is an odd child of its parent
E:nth-child(even) E is an even child of its parent
E:only-child E is the only child of its parent
E:checked E is an element that is has a checked attribute that is true (e.g. a radio or checkbox)
E:first the first E in the resultset
E:last the last E in the resultset
E:nth(n) the nth E in the resultset (1 based)
E:odd shortcut for :nth-child(odd)
E:even shortcut for :nth-child(even)
E:contains(foo) E's innerHTML contains the substring "foo"
E:nodeValue(foo) E contains a textNode with a nodeValue that equals "foo"
E:not(S) an E element that does not match simple selector S
E:has(S) an E element that has a descendent that matches simple selector S
E:next(S) an E element whose next sibling matches simple selector S
E:prev(S) an E element whose previous sibling matches simple selector S

4) CSS Value Selectors
E{display=none} css value "display" that equals "none"
E{display^=none} css value "display" that starts with "none"
E{display$=none} css value "display" that ends with "none"
E{display*=none} css value "display" that contains the substring "none"
E{display%=2} css value "display" that is evenly divisible by 2
E{display!=none} css value "display" that does not equal "none"

CSS Selectors - Speed Myths
prototype1.5.1/jQuery1.1.3.1/MooTools1.2dev/ext1.1rc1/dojoquery Speed Test
DomQuery is 2~3 times faster than jQuery/dojo/Mootools, Prototype is the most slowest one!

Methods for searching the DOM
- child
- contains
- down
- findParent
- findParentNode(or up)
- getNextSibling
- getPrevSibling
- is
- query
- select
- up


Dom Helper Methods
- append adds the new element as the last child of the context element
- insertAfter adds the new element directly after the context element
- insertBefore adds the new element directly before the context element
- insertFirst adds the new element as the first child of the context element
- overwrite overwrites the inner html of the context element


4,Observable/Events
An observable object can notify any number of observers who would like to know when an event happens and what happened.
Observable -----> Observer1
           -----> Observer2
           -----> Observer3
        notification

To create an Observable Class in Ext inherit from Ext.util.Observable
Use the inherited addEvents method to define events in the constructor
Ex:
var MyObservable = function(){
  this.addEvents({'event1': true,
                  'event2': true});
};
Ext.extend(MyObservable, Ext.util.Observable);

The MyObservable class inherits the following methods by inheriting Ext.util.Observable:
- addEvents
- add Listener(shorthand of on)
- fireEvent
- hasListener
- purgeListener
- removeListener(shorthand of un)

Observers can subscribe to the Observable object at any time by adding an event handler.
var myObservable = new MyObservable();
myObservable.on('event1', function(){console.log('event1 ran!');});

Observers can also unsubscribe at any time.
var myObservable = new MyObservable();
myObservable.on('event1', function() {console.log('event1 ran!');});
myObservable.un('event1', function() {console.log('event1 ran!');});
console.log(myObservable.hasListener('event1'));

Ext.util.Observable has 2 static methods:
- capture(Observable o, Function fn, [Object scope])
- releaseCapture(Observable o)

Capture is often useful to view the events which are firing and the order in which they fire
function captureEvents(observable) {
  Ext.util.Observable.capture(
    observable,
    function(eventName) {
      console.log(eventName);
    },
    this
  );
}
// then to use it...
captureEvents(myObservable);

ObservableStack is a simple stack data structure which can be observed:
- push
- pop

By creating an ObservableStack we can update multiple parts of a UI or communicate to multiple classes at the same time!
This way they always keep in sync with each other.

Events which may occur to an HTMLElement:
- mousedown
- mouseover
- click
- select
- blur
- focus
- change

Refer to Document Object Model Events

5,Widgets
Observable -> Component -> BoxComponent -> Container -> Panel    -> GridPanel -> EditorGridPanel
                        -> Button       -> Toolbar   -> Viewport -> FormPanel
                        -> Editor       -> Field                 -> TabPanel
                        -> DatePicker   -> Label                 -> TreePanel
                                                                 -> Window

Window/TabPanel

Ext.onReady(function(){
    var win;
    var button = Ext.get('show-btn');

    button.on('click', function(){
        // create the window on the first click and reuse on subsequent clicks
        if(!win){
            win = new Ext.Window({
                el:'hello-win',
                layout:'fit',
                width:500,
                height:300,
                closeAction:'hide',
                plain: true,
                
                items: new Ext.TabPanel({
                    el: 'hello-tabs',
                    autoTabs:true,
                    activeTab:0,
                    deferredRender:false,
                    border:false
                }),

                buttons: [{
                    text:'Submit',
                    disabled:true
                },{
                    text: 'Close',
                    handler: function(){
                        win.hide();
                    }
                }]
            });
        }
        win.show(this);
    });
});

EditableGridPanel

Ext.onReady(function(){
    // shorthand alias
    var fm = Ext.form;

    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store (created below)
    var cm = new Ext.grid.ColumnModel([{
           id:'common',
           header: "Common Name",
           dataIndex: 'common',
           width: 220,
           editor: new fm.TextField({
               allowBlank: false
           })
        },{
           header: "Light",
           dataIndex: 'light',
           width: 130,
           editor: new Ext.form.ComboBox({
               typeAhead: true,
               triggerAction: 'all',
               transform:'light',
               lazyRender:true,
               listClass: 'x-combo-list-small'
            })
        },{
           header: "Price",
           dataIndex: 'price',
           width: 70,
           align: 'right',
           renderer: 'usMoney',
           editor: new fm.NumberField({
               allowBlank: false,
               allowNegative: false,
               maxValue: 100000
           })
        },{
           header: "Available",
           dataIndex: 'availDate',
           width: 95,
           renderer: formatDate,
           editor: new fm.DateField({
                format: 'm/d/y',
                minValue: '01/01/06',
                disabledDays: [0, 6],
                disabledDaysText: 'Plants are not available on the weekends'
            })
        }
    ]);

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

    // this could be inline, but we want to define the Plant record
    // type so we can add records dynamically
    var Plant = Ext.data.Record.create([
           // the "name" below matches the tag name to read, except "availDate"
           // which is mapped to the tag "availability"
           {name: 'common', type: 'string'},
           {name: 'botanical', type: 'string'},
           {name: 'light'},
           {name: 'price', type: 'float'},             // automatic date conversions
           {name: 'availDate', mapping: 'availability', type: 'date', dateFormat: 'm/d/Y'},
           {name: 'indoor', type: 'bool'}
      ]);

    // create the Data Store
    var store = new Ext.data.Store({
        // load using HTTP
        url: 'plants.xml',

        // the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
               // records will have a "plant" tag
               record: 'plant'
           }, Plant),

        sortInfo:{field:'common', direction:'ASC'}
    });

    // create the editor grid
    var grid = new Ext.grid.EditorGridPanel({
        store: store,
        cm: cm,
        renderTo: 'editor-grid',
        width:600,
        height:300,
        autoExpandColumn:'common',
        title:'Edit Plants?',
        frame:true,
        plugins:checkColumn,
        clicksToEdit:1,

        tbar: [{
            text: 'Add Plant',
            handler : function(){
                var p = new Plant({
                    common: 'New Plant 1',
                    light: 'Mostly Shade',
                    price: 0,
                    availDate: (new Date()).clearTime(),
                    indoor: false
                });
                grid.stopEditing();
                store.insert(0, p);
                grid.startEditing(0, 0);
            }
        }]
    });

    // trigger the data store load
    store.load();
});

FormPanel

Ext.onReady(function(){

    // turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'side';

    var bd = Ext.getBody();

    /*
     * ================  Simple form  =======================
     */
    bd.createChild({tag: 'h2', html: 'Very Simple Form'});


    var simple = new Ext.FormPanel({
        labelWidth: 75, // label settings here cascade unless overridden
        url:'save-form.php',
        frame:true,
        title: 'Simple Form',
        bodyStyle:'padding:5px 5px 0',
        width: 350,
        defaults: {width: 230},
        defaultType: 'textfield',

        items: [{
                fieldLabel: 'First Name',
                name: 'first',
                allowBlank:false
            },{
                fieldLabel: 'Last Name',
                name: 'last'
            },{
                fieldLabel: 'Company',
                name: 'company'
            }, {
                fieldLabel: 'Email',
                name: 'email',
                vtype:'email'
            }, new Ext.form.TimeField({
                fieldLabel: 'Time',
                name: 'time',
                minValue: '8:00am',
                maxValue: '6:00pm'
            })
        ],

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

    simple.render(document.body);
});


6,Layout Managers
Container Layout

This is the base class for all other layout managers, and the default layout for containers when a specific layout is not defined.

Absolute Layout

This is a very simple layout that allows you to position contained items precisely via X/Y coordinates relative to the container.

Accordion Layout

The AccordionLayout contains a set of vertically-stacked panels that can be expanded and collapsed to display content. Only one panel can be open at a time.

Anchor Layout

This layout is for anchoring elements relative to the sides of the container. The elements can be anchored by percentage or by offsets from the edges, and it also supports a virtual layout canvas that can have different dimensions than the physical container.

Border Layout

This is the exact same layout style as BorderLayout in 1.x — layout regions with built-in support for nesting, sliding panels open and closed and splitters separating regions. This is the most common layout style for the primary UI in typical business applications.

Card Layout

CardLayout is a specific layout used in cases where a container holds multiple elements, but only a single item can be visible at any given time. Most commonly, this layout style is used for wizards, custom tab implementations, or any other use case requiring multiple, mutually-exclusive pages of information.

Column Layout

This is the layout style of choice for creating structural layouts in a multi-column format where the width of each column can be specified as a percentage or pixel width, but the height is allowed to vary based on content.

Fit Layout

This is a simple layout style that fits a single contained item to the exact dimensions of the container. This is usually the best default layout to use within containers when no other specific layout style is called for.

Form Layout

The FormLayout is a utility layout specifically designed for creating data entry forms. Note that, in general, you will likely want to use a FormPanel rather than a regular Panel with layout:'form' since FormPanels also provide automatic form submission handling. FormPanels must use layout:'form' (this cannot be changed), so forms needing additional layout styles should use nested Panels to provide them.

Table Layout

This layout style generates standard HTML table markup with support for column and row spanning.

7,Util
JSON
Modified version of Douglas Crockford"s json.js that doesn"t mess with the Object prototype http://www.json.org/js.html
- decode(String json) : Object
Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
- encode(Mixed o) : String
Encodes an Object, Array or other value

CSS
Utility class for manipulating CSS rules
- createStyleSheet( String cssText, String id ) : StyleSheet
Creates a stylesheet from a text blob of rules. These rules will be wrapped in a STYLE tag and appended to the HEAD of the document.
- removeStyleSheet( String id ) : void
Removes a style or link tag by id
- getRule( String/Array selector, Boolean refreshCache ) : CSSRule
Gets an an individual CSS rule by selector(s) 
- updateRule( String/Array selector, String property, String value ) : Boolean 
Updates a rule property

Date
The date parsing and format syntax is a subset of PHP's date() function, and the formats that are supported will provide results equivalent to their PHP versions. The following is a list of all currently supported formats:
Format  Description                                                               Example returned values
------  -----------------------------------------------------------------------   -----------------------
  d     Day of the month, 2 digits with leading zeros                             01 to 31
  D     A short textual representation of the day of the week                     Mon to Sun
  j     Day of the month without leading zeros                                    1 to 31
  l     A full textual representation of the day of the week                      Sunday to Saturday
  N     ISO-8601 numeric representation of the day of the week                    1 (for Monday) through 7 (for Sunday)
  S     English ordinal suffix for the day of the month, 2 characters             st, nd, rd or th. Works well with j
  w     Numeric representation of the day of the week                             0 (for Sunday) to 6 (for Saturday)
  z     The day of the year (starting from 0)                                     0 to 364 (365 in leap years)
  W     ISO-8601 week number of year, weeks starting on Monday                    01 to 53
  F     A full textual representation of a month, such as January or March        January to December
  m     Numeric representation of a month, with leading zeros                     01 to 12
  M     A short textual representation of a month                                 Jan to Dec
  n     Numeric representation of a month, without leading zeros                  1 to 12
  t     Number of days in the given month                                         28 to 31
  L     Whether it's a leap year                                                  1 if it is a leap year, 0 otherwise.
  o     ISO-8601 year number (identical to (Y), but if the ISO week number (W)    Examples: 1998 or 2004
        belongs to the previous or next year, that year is used instead)
  Y     A full numeric representation of a year, 4 digits                         Examples: 1999 or 2003
  y     A two digit representation of a year                                      Examples: 99 or 03
  a     Lowercase Ante meridiem and Post meridiem                                 am or pm
  A     Uppercase Ante meridiem and Post meridiem                                 AM or PM
  g     12-hour format of an hour without leading zeros                           1 to 12
  G     24-hour format of an hour without leading zeros                           0 to 23
  h     12-hour format of an hour with leading zeros                              01 to 12
  H     24-hour format of an hour with leading zeros                              00 to 23
  i     Minutes, with leading zeros                                               00 to 59
  s     Seconds, with leading zeros                                               00 to 59
  u     Milliseconds, with leading zeros                                          001 to 999
  O     Difference to Greenwich time (GMT) in hours and minutes                   Example: +1030
  P     Difference to Greenwich time (GMT) with colon between hours and minutes   Example: -08:00
  T     Timezone abbreviation of the machine running the code                     Examples: EST, MDT, PDT ...
  Z     Timezone offset in seconds (negative if west of UTC, positive if east)    -43200 to 50400
  c     ISO 8601 date                                                             2007-04-17T15:19:21+08:00 or
                                                                                  2007-04-17T15:19:21Z
  U     Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)                1193432466 or -2138434463

Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
// Sample date:
// 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
document.write(dt.format('Y-m-d'));                         // 2007-01-10
document.write(dt.format('F j, Y, g:i a'));                 // January 10, 2007, 3:05 pm
document.write(dt.format('l, \\t\\he jS of F Y h:i:s A'));  // Wednesday, the 10th of January 2007 03:05:01 PM

Here are some standard date/time patterns that you might find helpful. They are not part of the source of Date.js, but to use them you can simply copy this block of code into any script that is included after Date.js and they will also become globally available on the Date object. Feel free to add or remove patterns as needed in your code.
Date.patterns = {
    ISO8601Long:"Y-m-d H:i:s",
    ISO8601Short:"Y-m-d",
    ShortDate: "n/j/Y",
    LongDate: "l, F d, Y",
    FullDateTime: "l, F d, Y g:i:s A",
    MonthDay: "F d",
    ShortTime: "g:i A",
    LongTime: "g:i:s A",
    SortableDateTime: "Y-m-d\\TH:i:s",
    UniversalSortableDateTime: "Y-m-d H:i:sO",
    YearMonth: "F, Y"
};

Example usage:
var dt = new Date();
document.write(dt.format(Date.patterns.ShortDate));


8,jQuery/Prototype/yui Bridge

Ext support jQuery、Prototype/script.aculo.us and yui integration.
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics