extjs
TRANSCRIPT
EXTJS
G I R I S H S R I V A S T A V A
G I R I S H 0 9 2 . C H @ G M A I L . C O M
2
Module 1(Day1): JavaScriptThe lessons covered in this module include:• DHTML• Introduction to JavaScript• Elements of JavaScript Program• JavaScript Statements• Functions• Objects• Defining Objects• Arrays• Events• Time Outs• Integrating JavaScript with Java• Creating Windows• Summary• Examples and Exercises
Module 2 (Day2): ExtJs• Introduction of ExtJs• Getting Started• Fundamental Classes• Event Handling• Component Model• Examples
Module 3 (Day3): ExtJs cont…• Getting Started with Sencha Architect• Create and Configure Components• Create/Configure Data Stores• Templates & DataView• Creating & Extending Classes• Examples
Module 4 (Day4): ExtJs cont…
• Internationalization• Drag & Drop• Hands-on Experience w/ Common Components• TabPanel• GridPanel• TreePanel• FormPanelBuilding a Theme• Application Best Practices
6
Objectives
At the end of this module you will be able to:1. Write JavaScript code using all the basic elements
of JavaScript Programs2. Create Windows & Dialog Boxes3. Use the JavaScript’s in-built objects in a web page 4. Write code that does Event Handling in HTML pages5. Manipulate HTML Forms through JavaScript
dynamically6. Integrate Java and JavaScript through Applets
7
DHTML
DHTML stands for Dynamic Hyper Text Markup Language which
helps to add Dynamic content to static HTML pages.
8
Introduction to JavaScript
JavaScript is:1. An easy to use object scripting language2. Designed for creating live online applications3. Code is included as part of a HTML document4. Scripts are run by the Web browser
9
Introduction to JavaScript: JavaScript Versus Java
1. JavaScript can be combined directly with HTML
2. The JavaScript language structure is simpler than that of Java
3. JavaScript is a purely interpreted language
4. The JavaScript interpreter is built into a Web browser
10
Introduction to JavaScript: Using the SCRIPT Tag
<HTML> <HEAD> <TITLE>Simple JavaScript Example </TITLE> </HEAD> <BODY> HTML Text goes here. <SCRIPT LANGUAGE="JavaScript"> document.write("Here is my output.") </SCRIPT> </BODY></HTML>
11
Elements of JavaScript Program
Elements of JavaScript Program can be divided into five categories, as
follows:1. Variables2. Expressions3. Control Structures4. Functions5. Objects and Arrays
12
Elements of JavaScript Program: Variables
• Data Types
• Rules for variable names
• Type Casting
• Variable Declaration and Scope
18
JavaScript Statements: while Statement
• A while statement executes its statements as long as a specified condition evaluates to true. A ‘while’ statement looks as follows:
while (condition) { statements}
19
Functions
• Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure: a set of statements that performs a specific task. To use a function, you must first define it, then your script can call it. A function definition looks as follows:
function gcd(m,n) { return n > 0 ? gcd(n,m%n) : m ; }
20
Objects
• An object is a self-contained unit of code having the following characteristics:– Properties– Methods– Identity
21
Objects: The Window Object
• At the top of the browser hierarchy is the window object, which represents a browser window
• The properties/methods of this object are:– status– alert()– confirm()– prompt()
22
Objects: The Document Object
Represents characteristics of the current HTML page.• Some of its properties are:
– title - lastModified– fgColor - bgColor
• Some of its methods are:– write()– writeln()
• In the browser object hierarchy, the document object is contained in a window object (for a page without frames)
23
Objects: The Form Object
• Represents an HTML Form.
• Has the same name as the NAME attribute in the FORM tag
• In the browser object hierarchy, the form object is contained in the document object
24
Objects: Frame Objects
• Each Frame in a frame set is represented as a frame object
• A frame set contains an array of frame objects representing all the frames in it
• You can refer to a particular frame :– By name - if it has one– By reference to the parent and the array index of that
frame
25
Objects: The Math Object
• The Math object can’t be created, since it exists automatically in all Java Script Programs
• Its properties represent mathematical constants
• Its methods are mathematical functions
26
Objects: The String Object
• Any String variable in JavaScript is a String object. It has a property– Length and – Many Methods
27
Objects: The Date Object
• Is built-in JavaScript object
• Create using new keyword
29
Defining Objects
The object definition is a simple function that accepts parameters to
initialize a new object and assigns those to the corresponding
properties.
31
Defining Objects: Looping through Object’s Properties
• The final statement used for object-oriented work in JavaScript is the for...in loop
• This loop executes once for each property of an object, assigning the index variable to the property name.
32
Arrays
• JavaScript doesn’t support array variables
• Arrays need to be created using array object
33
Events
• Are things that happen to the browser
• Used to trigger portions of program
• Pertain to the web page containing the script
34
Events: Event Handlers
• Embedded in HTML tags as part of anchor and links or any of the form element tags.
35
Events• Some (but not all) elements on the web page
respond to user interactivity (keystrokes, mouse clicks) by creating events– Different kinds of elements produce different events
• Browsers are not all alike in what events are produced– We will concentrate on events from HTML form
elements and commonly recognized events• You can put handlers on HTML form elements
– If the event isn’t generated, the handler does nothing– A handler should be very short
• Most handlers call a function to do their work
36
A simple event handler• <form method="post" action="">
<input type="button" name="myButton" value="Click me" onclick="alert('You clicked the button!');"></form>– The button is enclosed in a form
• method tells how to send the form data; action tells where to send it– The tag is input with attribute type="button"– The name can be used by other JavaScript code– The value is what appears on the button– onclick is the name of the event being handled
• The value of the onclick element is the JavaScript code to execute• alert pops up an alert box with the given text
37
Capitalization• JavaScript is case sensitive• HTML is not case sensitive• onclick="alert('You clicked the button!');"
– The red underlined parts are HTML– The quoted string is JavaScript– You will frequently see onclick capitalized as onClick
• The Java naming convention is easier to read• This is fine in HTML, but an error if it occurs in JavaScript
• Also note: Since we have a quoted string inside another quoted string, we need both single and double quotes
38
Common events• Most HTML elements produce the following events:
– onClick -- the form element is clicked– onDblClick -- the form element is clicked twice in close succession– onMouseDown -- the mouse button is pressed while over the form
element– onMouseOver -- the mouse is moved over the form element – onMouseOut -- the mouse is moved away from the form element– onMouseUp -- the mouse button is released while over the form
element– onMouseMove -- the mouse is moved
• In JavaScript, these must be spelled in all lowercase
39
Example: Simple rollover• The following code will make the text Hello
red when the mouse moves over it, and blue when the mouse moves away<h1 onMouseOver="style.color='red';"
onMouseOut="style.color='blue';">Hello </h1>
• Image rollovers are just as easy:<img src="../Images/duke.gif"
width="55" height="68" onMouseOver="src='../Images/duke_wave.gif';" onMouseOut="src='../Images/duke.gif';">
40
Events and event handlers I• The following tables are taken from:
http://developer.netscape.com/docs/manuals/js/client/ jsguide/index.htm
Event Applies to Occurs when Handler
Load Document body
User loads the page in a browser
onLoad
Unload Document body
User exits the page
onUnload
Error Images, window
Error on loading an image or a window
onError
Abort Images User aborts the loading of an image
onAbort
41
Events and event handlers IIEvent Applies to Occurs
whenHandler
KeyDown
Documents, images, links, text areas
User depresses a key
onKeyDown
KeyUp Documents, images, links, text areas
User releases a key
onKeyUp
KeyPress
Documents, images, links, text areas
User presses or holds down a key
onKeyPress
Change Text fields, text areas, select lists
User changes the value of an element
onChange
42
Events and event handlers IIIEvent Applies to Occurs
whenHandler
MouseDown Documents, buttons, links
User depresses a mouse button
onMouseDown
MouseUp Documents, buttons, links
User releases a mouse button
onMouseUp
Click Buttons, radio buttons, checkboxes, submit buttons, reset buttons, links
User clicks a form element or link
onClick
43
Events and event handlers IVEvent Applies to Occurs
whenHandler
MouseOver Links User moves cursor over a link
onMouseOver
MouseOut Areas, links
User moves cursor out of an image map or link
onMouseOut
Select Text fields, text areas
User selects form element’s input field
onSelect
44
Events and event handlers V
Event Applies to
Occurs when Handler
Move Windows User or script moves a window
onMove
Resize Windows User or script resizes a window
onResize
DragDrop Windows User drops an object onto the browser window
onDragDrop
45
Events and event handlers VIEvent Applies to Occurs
whenHandler
Focus Windows and all form elements
User gives element input focus
onFocus
Blur Windows and all form elements
User moves focus to some other element
onBlur
Reset Forms User clicks a Reset button
onReset
Submit Forms User clicks a Submit button
onSubmit
JavaScript and HTML Forms
• Object Model for the Browser Window– Compound object structure is created when a web
page loads into a browser• Hierarchy
– Window is an object, the HTML document is an object and its elements are objects
– These objects have primitives associated with them
JavaScript and HTML Forms
• window [closed, location]
– history [length]
– document [bgColor, fgColor, URL, lastmodified,linkColor, vlinkColor]
» images [properties]» links [properties]» frames [properties]» forms [properties]
JavaScript and HTML Forms
• Window object is parent of structure– window.closed is primitive that is Boolean– window.location primitive contains string of the URL of the
HTML file– window.document object is primary focus
• When web page is loaded the HTML elements assign values to most of these window.document primitives
• Often the word window is excluded as in document.write but need it if referring to multiple open windows
• Properties can also be objects
JavaScript and HTML Forms• <HTML>• <HEAD>• <TITLE>Document Properties</TITLE>• <SCRIPT LANGUAGE=JavaScript><!--• document.write(closed);• document.write("<BR>"+ document.bgColor);• document.write("<BR>"+document.fgColor);• document.write("<BR>"+document.lastModified);• //--></SCRIPT>• </HEAD>• <BODY TEXT="#0000FF" BGCOLOR="#FFFFCC">• <P>Blue text on a yellow background.<BR>• <SCRIPT LANGUAGE=JavaScript><!--• document.write("<BR>"+ document.bgColor);• document.write("<BR>"+document.fgColor);• //--></SCRIPT>• </BODY>• </HTML>
JavaScript and HTML Forms
• Methods– Behavior associated with an object– Essentially functions that perform an action– Some are built in and others user made
• Built-In Methods of the window object– Confirm– Alert– Prompt
JavaScript and HTML Forms
• User Events– An event occurs when a user makes a change to a
form element• Ex. Click a button, mouseover an image
– Detection of an event done by event handlers– Event handler is an attribute of the HTML button– <form>
• <input type=button value=“please click” onclick=“function name()”>
– </form>
JavaScript and HTML Forms• <HTML>• <HEAD>• <SCRIPT LANGUAGE=JavaScript><!--• function changecolor(){• document.bgColor="#ff0000";• }• //--></SCRIPT>• </HEAD>• <BODY>• <P><FORM >• <P><INPUT TYPE=button VALUE="Click Me" onclick="changecolor()">• </FORM>• </BODY>• </HTML>
JavaScript and HTML Forms
• Form Object– Window.document.form– A form is a property of the document but is also an
object– Form elements are properties of a form and are
also objects– Access to form’s properties is done through the
NAME attribute of the FORM tag– Access to the properties of the form elements is
done through the NAME attributes of the particular form element
JavaScript and HTML Forms
Inte
ract
ive
Pro
gra
mm
ing
on
th
e
Inte
rne
t ,K
nu
ckle
s
JavaScript and HTML Forms• <HTML>• <HEAD>• <SCRIPT LANGUAGE=JavaScript><!--• function plus(){• var n1;• var n2;• n1=document.addmult.num1.value;• n2=document.addmult.num2.value;•• n1=parseFloat(n1);• n2=parseFloat(n2);••
document.addmult.result.value=n1+n2;• }• function times(){• var n1;• var n2;• n1=document.addmult.num1.value;• n2=document.addmult.num2.value;•• n1=parseFloat(n1);• n2=parseFloat(n2);••
document.addmult.result.value=n1*n2;• }
• //--></SCRIPT>• </HEAD>• <BODY BGCOLOR="#FFFFCC">• <P><FORM name=addmult>• <P>Enter a number in each field:• <INPUT TYPE=text NAME=num1 VALUE="" SIZE=5>• <INPUT TYPE=text NAME=num2 VALUE="" SIZE=5><BR>• <INPUT TYPE=button VALUE="+" onclick="plus()">• <INPUT TYPE=button VALUE="*" onclick="times()"><BR>• <INPUT TYPE=reset VALUE="Reset Form"><BR>• <TEXTAREA NAME=result ROWS=3 COLS=27 WRAP=virtual></TEXTAREA>• </FORM>• </BODY>• </HTML>
JavaScript and HTML FormsForm for submitting info for server side processing
Inte
ract
ive
Pro
gra
mm
ing
on
th
e
Inte
rne
t ,K
nu
ckle
s
JavaScript and HTML Forms• <HTML>• <HEAD>• <SCRIPT LANGUAGE=JavaScript><!--• function verify(){• with(document.infoform){• if((fullname.value=="")||(address.value=="")||(email.value=="")){• alert("You have left one or more fields blank. Please supply the necessary information, and re-submit the
form.");• }• else {• display.value="The following information has been added to our
guestbook:\r"+fullname.value+"\r"+ address.value +"\r" +email.value;• }• }• }• //--></SCRIPT>• </HEAD>• <BODY BGCOLOR="#FFFFCC">• <P><FORM name=infoform>• <P><TABLE BORDER=0>• <TR>• <TD WIDTH=83>• <P>Name:• </TD>• <TD>• <P><INPUT TYPE=text NAME=fullname VALUE="" SIZE=32>• </TD>• </TR>
• <TR>• <TD WIDTH=83>• <P>Address:• </TD>• <TD>• <P><INPUT TYPE=text NAME=address VALUE="" SIZE=32>• </TD>• </TR>• <TR>• <TD WIDTH=83>• <P>E-mail:• </TD>• <TD>• <P><INPUT TYPE=text NAME=email VALUE="" SIZE=32>• </TD>• </TR>• <TR>• <TD WIDTH=83>• <P><INPUT TYPE=button VALUE="Submit" onclick="verify()">• </TD>• <TD>• <P><INPUT TYPE=reset VALUE="Clear Your Information">• </TD>• </TR>• <TR>• <TD COLSPAN=2>• <P><TEXTAREA NAME=display ROWS=5 COLS=41 WRAP=virtual></TEXTAREA>• </TD>• </TR>• </TABLE>
• </FORM>• </BODY>• </HTML>
58
Time Outs
• Statements that will be executed after a certain amount of time elapses
• Handy for periodically updating a Web Page or for delaying the display of a message or execution of a function
59
Summary
In this module you have learnt to:• Write JavaScript code using all the basic elements
of JavaScript Programs• Create Windows & Dialog Boxes• Use the JavaScript’s in-built objects in a web page • Write code that does Event Handling in HTML pages• Manipulate HTML Forms through JavaScript
dynamically• Integrate Java and JavaScript through Applets
Introduction to ExtJS Framework
Introduction to ExtJS
ExtJS is a java-script framework (client-side) that enables developers to develop Rich Internet Applications (RIA) (static websites or data-driven applications) with a large number of options.ExtJS has a huge collection of controls (ranging from textboxes to highly sophisticated UI Controls) along with a brilliant demo + examples.
• Since ExtJS is a java-script framework, all of the java script rules are applicable for ExtJS.
• ExtJS makes excellent & extensive use on DOM, CSS etc.
• ExtJS is case-sensitive, i.e., a != A • ExtJS is “Asynchronous” by default.
Points to Remember
WHY EXT JS ?
• This is really what matters (MVC)o Easy Client-side data modeling
Relational Modelso Simple to use GUI widgets
Why we use Extjs?
• The chart below shows statistics of distribution 10 most popular JS Libraries
Why we use Extjs?
• The chart below shows statistics of distribution 10 most popular JS Libraries
Where is Extjs on this chart?
Why we use Extjs?
• JQuery29.92%• SWFObject13.12%• Adobe Active Content6.74%• Prototype5.5%• Facebook Connect5.19%• Yahoo User Interface4.72%• script.aculo.us4.01%• jQuery UI3.39%• PNG Fix3.11%• MooTools2.67%• Google JS Api1.76%• JCarousel1.41%• AC_OETags1.3%• Flash Object1.03%• JQuery Easing0.93%• JQuery UI Tabs0.83%• JQuery Validate0.81%• JQuery Dimensions0.77%
ie7-js0.14%CSS Browser Selector0.14%IE Update0.14%SoThink HTML Menu0.14%Lytebox0.13%Highslide0.11%JQuery Preload0.1%Firebug Lite0.1%Direct Web Remoting0.1%Bit.ly Javascript API0.1%
Extjs 0.09%HTML 5 Shiv0.09%Prototip0.09%Hier Menus0.08%
SuperFish0.73%cufón0.59%JCarousel Lite0.55%JSON0.54%Flash Detect0.48%Dojo Toolkit0.46%JQuery ScrollTo0.44%Shadowbox0.38%Javascript Tooltips0.37%SWF Address0.36%Adobe Spry0.34%Milonic0.32%overLIB0.28%BBC Glow0.27%MM Menu0.27%Style Switcher0.21%Nifty Corners0.2%Google Friend Connect0.15%
MVC
• Why is MVC so important?o In this case, it is because it is 100%, agent-based, client
side codeo This means typical MVC on the server is not needed
Good or Bad? Design decision
Server Side MVC
Server Side Models
• Server Side Models are simple classes that house an 'instantiated' version of a resource recordo Resource Records can be a row from a MySql Table,
required parameters from another server public api, web service, etc
• These models should be transparent to the controller on how the raw data is represented, but rather be in a specified format for the controller
Server Side Models
• To facilitate how the model instantiates data, usually a map is present
• The Map is capable of understanding how to speak with the resourceo "Select `id`, `first`, `last` from `names`......
• The model would then have member variables:o $model->ido $model->firsto $model->lasto ....
Server Side Models
• All of my models have key featureso 1-to-1 resource mappingo $model->save()o $model->find()o $model->delete()
• Similar to CRUD operations except I leave save() to determine wether it is Create or Updateo CRUD === 'Create Read Update Destroy'
Server Side Views
• Sever Side View classes, for most frameworks, take the model data and return the requested type of viewo echo($view->buildTable(records));
• This buildTable() function is called by a controller, who then echo()'s the html generated by the view
• Has one major faulto What happens when I want to use this server side stack
for mobile apps?• Are there any performance flaws?
Server Side Control
• We have seen that how models and views worko These require some sort of delegation
• Controllers will receive the request from the client (old view), do any preprocessing, call the model (CRUD), use the model data, call the view, and return the html
• Within this return, we usually find JavaScript embedded as a code agent to 'enchance' our viewing pleasure.
• What if we mixed this up a bit and used JavaScript as our primary source of control?
Client Side JS with ExtJS
• MVC for JavaScript• Exactly same process for server side stack, except we
now try to use the server as little as possibleo This allows for powerful client machines to do most of
our processing and renderingo Only allow the client to manipulate data that can be
considered hostile!
ExtJS Models
• The most important feature of ExtJSo Can have relational models!!!!!!! o Example:
Orders (a model) can have many Order Items (another model)
o Each record of orders is stored in storeo Each record of orders points to another store that has
its Order itemso This allows us to select an order, and then immediately
have access to all its order items
ExtJS View
• Since this is JavaScript, we immediately expect robust GUI widgets
• Of course, you can add CSS and style them
ExtJS Control
• JavaScript is a functional languageo This allows for very strong and very easy control logic
o Of course, you can still use OOP style if desired
So how does this all work?
• By using MVC on the client side:o We only need to contact the server when using
CRUD operationso By control logic when otherwise needed
• Lets go through an example
EXT Windows looks like OS windows – support dragging/resizing/closing
Good Documentation
EXT JS SAMPLES
Community Support
Cross Browser
Adapters
Commercial and Open Source License
WIDGETS PROVIDED BY EXTJS
WINDOW
Combobox
Data gridsortcolumnseditabledatasource
CHART
CALENDAR
Getting Started
Download: http://sencha.com/products/extjs/download.php
1) Create a Web Project.2) Paste all mandatory extjs related files
in a separate folder or resource folder , name it extjs folder or whatever.
Exploring Folder structure of ExtJS
• The unzipped files look like this (the folder structure might slightly differ based on
the version of ExtJS you download).• adapter: This folder contains the core
engine files (basic foundation) of ExtJS. Also provides interaction with other libraries like YUI, jQuery etc.
• docs: This contains the complete UI7 documentation for ExtJS. This is an excellent source of information.
12/04/2023 111Beginning ExtJS with ASP.NET - Lesson 01 - Part two
Exploring Folder structure…
• examples: A must-see list of well categorized brilliant demo of Ext examples.
• resources: Contains all CSS, images, sprites required by Ext.
• src: Contains all the source files of ExtJS. (Altering & playing with these (“src”) files are strictly for advanced professionals )
12/04/2023 112Beginning ExtJS with ASP.NET - Lesson 01 - Part two
Files to be linked• Add links to all the highlighted files. These files are
very much important to set-up the ground work for our application.
• Example: <link href="ExtJS/resources/css/ext-all.css"
rel="stylesheet" type="text/css" /><script type="text/javascript" language="javascript"
src="ExtJS/adapter/ext/ext-base.js"></script> <script type="text/javascript" language="javascript"
src="ExtJS/ext-all.js"></script>
Explaining the files to be linked …
• ext-base.js: This file is the driving engine of Ext. This file is very important & cannot be skipped.
• ext-all.js: This file contains all the defined UI elements (like textbox, combo, button, grid etc…) found in the samples & demo link (except ux type controls). Using this file is highly recommended for beginners. Advanced professionals can replace this with a custom build file.
• ext-all.css: Responsible for the default blue theme of ExtJS.
EXAMPLE OF HELLO WORLD ALERT WINDOW
Hello World
RESULT
EXAMPLE OF CREATING TABS
HTML CODE
JS CODE
RESULT:
Our first Hello Ext!!!Add a java script named “default.js” and place it within a folder named “Scripts” within the root directory.Start editing your default.js file and add / copy & paste the following contents.
Ext.onReady(function(){Ext.MessageBox.show({
title: ’My Message’ , msg: ’My first Hello world using Ext…’, buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.INFO
});});
12/04/2023 123
Hello World with ExtJS…
Eureka!!!, there we go…
12/04/2023 124
A close look at our code & outputOur code
Ext.MessageBox.show({title:’My Message’ , msg:’My first Hello world using Ext…’, buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.INFO
});
Output
(edited image generated as output).
The values we specified appear as expected in the output. Kindly correlate the input values & output in the “name: value” format.
12/04/2023 125
Analyzing code & output... • Unlike the traditional alert box, Ext Messagebox can
be highly customized. This is the flexibility ExtJS offers for developers. It is recommended to take a look at the Message box example in the Ext virtual directory you configured for Ext.
• And, as you might have observed, displaying a message box requires you to specify every piece of information, in the “name: value” format (Example:- title:’ My Message’). This “name: value” would be followed through out Ext programming.
12/04/2023 126Beginning ExtJS with ASP.NET - Lesson 01 - Part two
Analyzing code…• In our Ext.MessageBox example, all the four
“name: value” pairs are passed within a pair of curly braces “{ }” to the .show() method of Ext.
Ext.MessageBox.show( { title:’Hello World’ } );
• The yellow highlighted part is called as “config” object (or) “configuration object”, since this is the deciding authority & instructs Ext, as how to render (display) the Ext Message box.
12/04/2023 127
Additional Info on config objects
• More than one items within a config object are comma “,” delimited (separated using a comma).
• Almost all Ext components have config objects, mostly passed as constructors. Nesting of config objects are permitted.
• Take care to close the curly braces / square braces in the descending order in which they are opened, i.e., last opened bracket is closed first.
TIP
12/04/2023 128
Looking at an Asynchronous Ext!Ext.onReady(function(){
// rest of code follows
});
What is Ext.onReady() ?Is is an event. “onReady” is the first event that fires when the DOM is constructed by the browser.
• As denoted at the beginning of this lesson, Ext is asynchronous (by default).
• The code within the function would execute only after the “onReady” event.
• Understanding the async nature makes a long step in programming with Ext.
12/04/2023 129
When Ext.onReady() fires?
Client browser Web Server ASP.Net Life Cycle
Parsed contentsBrowser
generates the page
On after generation,
Ext.onReady() fires
1 2 3
6 5 4 130
Explaining the sequence…• 1 to 2: The client browser makes a request to a
web page at the web-server.• 2 to 3: Web server acknowledges the request,
loads the page & executes it. Execution includes all server side application logic (making DB calls / file IO etc) in .net compliant language.
• @ stage 3: This shows the life cycle of any web-form from “PreInit” event to “Unload” event.
12/04/2023 131
Explaining the sequence…• @ stage 4: Once all server-side events are fired
and execution is completed, web server constructs the output form with all required CSS, js files and sends the contents to the browser.
• @ stage 5: Browser receives the contents sent by server, parses & generates the page, and finally renders to the user.
• Once all the HTML elements are generated, the DOM is said to be ready. All the js files linked with the page, are cached in the local machine.
12/04/2023 132
Explaining the sequence…
• @ stage 6: Once all the js files are completely cached locally & the DOM is ready, the Ext.onReady() event fires.
• It is at this stage, the ExtJS code is loaded from the js files and the UI is rendered / front end execution begins.
• ExtJS codes are loaded & executed in the order in which the js files are linked in the aspx page.
12/04/2023 133
onReady & Async nature
• Like any Ext application, in our “Hello world” example, the message box code executes only after Ext.onReady() event.
• Thereby care must be taken as to know & understand, when the components are rendered and when & how they are available for accessibility.
• Failing to do this, would throw “Ext.getCmp(‘’) is null or not an object” script error message.
12/04/2023 134
What else extjs can do?• Ajax support• Dom traversing• Dom manipulation• Event Handling• Selectors• OOP emulation• Animation
Main extjs classes• Component• Panel• Observable• Store
Component
• All widgets extends component class• Provide base widget functions like
– enable()/disable()– show()/hide()– addClass()/removeClass()– update(data/html) – update content area– getEl() return element– getId()– getXType()– render(target)– focus()
• XType – alternate way to define component
– Lazy component creation• var panel1 = {• xtype : 'panel',• title : 'Plain Panel',• html : 'Panel with an xtype specified'• }• var myPanel = new Ext.Panel({ • renderTo : document.body, • height : 50, • width : 150, • title : 'Panel', • frame : true
• Components are managed by Ext.ComponentMgr
– get(componentId)– registerType(xtype, object) (shorthand Ext.reg())
Containers
• handle the basic behavior of containing items, namely adding, inserting and removing items
• Main functions– add()– remove()/removeAll()– insert()– find()/findBy()/findById()/findByType– doLayout()– get(index or
id)/getComponent(component or index or id)
• Main prop– Items - MixedCollection of children
components
Panels• Main panel functions/prop/conf prop
– load()– panel.load({– url: 'your-url.php',– params: {param1: 'foo', param2: 'bar'}, // or a URL encoded string– callback: yourFunction,– scope: yourObject, // optional scope for the callback– discardUrl: false,– nocache: false,– text: 'Loading...',– timeout: 30,– scripts: false– });
– body – prop– html – conf prop– autoLoad – conf prop
• Toolbar and Bottombar• Panel subclasses
– TabPanel– Window – FormPanel– GridPanel – TreePanel
Layouts
• Layouts manages by containers – there is no need to create Layouts directly
• The most useful are Fit, VBox, HBox, Border– Only VBox, HBox, Border layouts
supports margins• Flex prop of VBox, HBox• BorderLayout must have center
item• Table layout does not support
resizing of items
ExtJS Classes
Creating Classes
• Creating classes in JavaScript is easy as creating a constructor function and using the new keyword when creating an instance of that class.
Person Class:
var Person = function(config) { Ext.apply(this, config);
};
Using the Person class:
var me = new Person({fName: ‘Aaron’,lName: ‘Conran’, dob: ’03/23/1984’});
Fundamental Classes• Ext.Element
– Encapsulates a DOM element, adding simple DOM manipulation facilities, normalizing for browser differences.
– The events documented in this class are not Ext events, they encapsulate browser events.
• Usage:// by id – var el = Ext.get("my-div");
• // by DOM element reference – var el = Ext.get(myDivElement);
Cont…• get( el ) : Element
– Retrieves Ext.Element objects.– This method does not retrieve Components. This method
retrieves Ext.Element objects which encapsulate DOM elements.
Methods– addBehaviors( obj )
• Applies event listeners to elements by selectors when the document is ready. ...
– apply( obj, config, defaults ) : Object• Copies all the properties of config to obj. ...
– applyIf( obj, config ) : Object• Copies all the properties of config to obj if they don't already exist. ...• Etc.
Some methods Present in Ext.Element– new Ext.Element( element, [forceNew] ) : Ext.Element
• Create a new Element directly. ...
– getAttribute( name, [namespace] ) : String★• Returns the value of an attribute from the element's underlying DOM
node. ...
– getBorderWidth( side ) : Number• Gets the width of the border(s) for the specified side(s) ...
– getBottom( local ) : Number• Gets the bottom Y coordinate of the element (element Y position +
element height) ...
– getBox( [contentBox], [local] ) : Object• Return an object defining the area of this Element which can be
passed to setBox to set another Element's size/locati...
– And many more…(http://docs.sencha.com/ext-js/3-4/#!/api/Ext.Element)
Ext.CompositeElement• This class encapsulates a collection of DOM
elements, providing methods to filter members, or to perform collective actions upon the whole set.
• Although they are not listed, this class supports all of the methods of Ext.Element.
• All methods return this and can be chained.
Usage:var els = Ext.select("#some-el div.some-class", true); // or select directly from an existing element var el =
Ext.get('some-el'); el.select('div.some-class', true);
els.setWidth(100); // all elements become 100 width els.hide(true); // all elements fade out and hide // or els.setWidth(100).hide(true);
Some methods present in Ext.CompositeElement
– add( els ) : CompositeElement• Adds elements to this Composite object. ...
– clear( )• Removes all elements. ...
– getCount( )• Returns the number of elements in this Composite. ...
– indexOf( el )• Find the index of the passed element within the composite
collection. ...
– item( index ) : Ext.Element• Returns a flyweight Element of the dom element object at the
specified index ...
– And many more…(http://docs.sencha.com/ext-js/3-4/#!/api/Ext.CompositeElement)
Ext.DomHelper• The DomHelper class provides a layer of
abstraction from DOM and transparently supports creating elements via DOM or using HTML fragments.
• It also has the ability to create HTML fragment templates from your DOM building code.
• A specification object is used when creating elements.
Cont…• Attributes of this object are assumed to be
element attributes, except for 4 special attributes:– tag :The tag name of the element– children : or cn
• An array of the same kind of element definition objects to be created and appended. These can be nested as deep as you want.
– cls :The class attribute of the element. This will end up being either the "class" attribute on a HTML fragment or className for a DOM node, depending on whether DomHelper is using fragments or DOM.
– html :The innerHTML for the element
Methods• append( el, o, [returnElement] ) : HTMLElement/Ext.Element
– Creates new DOM element(s) and appends them to el. ...
• applyStyles( el, styles )– Applies a style specification to an element. ...
• insertAfter( el, o, [returnElement] ) : HTMLElement/Ext.Element– Creates new DOM element(s) and inserts them after el. ...
• insertBefore( el, o, [returnElement] ) : HTMLElement/Ext.Element– Creates new DOM element(s) and inserts them before el. ...
• insertFirst( el, o, [returnElement] ) : HTMLElement/Ext.Element– Creates new DOM element(s) and inserts them as the first child of
el. ...• insertHtml( where, el, html ) : HTMLElement
– Inserts an HTML fragment into the DOM. ...
Example• This is an example, where an unordered list with 3 children items is
appended to an existing element with id 'my-div':
Ext.apply• Ext.apply copies all attributes of one object to another.• Ext.apply is often used at the beginning of constructors to
copy configuration arguments to the this scope.• The new keyword creates a new blank object in the scope of
this.• You can also supply a 3rd argument as a default configuration.
Ex:
Ext.apply(this, config);
// with defaults
var defConfig = {test: ‘abc’};
Ext.apply(this, config, defConfig);
Ext.applyIf
• Ext.applyIf works similarly to Ext.apply except if properties already exist they won’t be overwritten.
• Ex:var point = point || {};var default = {x: 0, y: 0};Ext.applyIf(point, default);
Ext.extend• Ext.extend is used to extend or inherit from classes
which already exist.• Generic Pattern:
var SubClass = function() { SubClass.superclass.constructor.call(this);};Ext.extend(SubClass, BaseClass, { newMethod : function() {}, overriddenMethod : function() {}};
• SubClass extends BaseClass and overrides overridenMethod and adds newMethod.
superclass.constructor
• The superclass.constructor property points to our base (or super) class constructor.
• We use the JavaScript call method to run the constructor in the scope of this.
• this will always be our first argument of call. Other arguments will be passed to our base constructor:
• Ex:BaseClass.superclass.constructor.call(this, config);
Extending an Ext Class
• Extending and Customizing Ext classes is easy• Goal: Create a extension of BasicDialog
– New class DefaultDialog which extends from BasicDialog
– Provide a set of defaults for dialogs• modal, width, height, shadow, draggable, etc
– No need to add/override methods to BasicDialog
Extending an Ext class var DefaultDialog = function(config) {
var config = config || {}; // default config to blank object var defConfig = {title: 'Default', // provide a default config
height: 130, width: 250, shadow: true, modal: true, draggable:true, fixedcenter:true, collapsible: false, closable: true, resizable:false};
Ext.applyIf(config, defConfig); // apply defConfig IF config does not have propertyvar el = Ext.DomHelper.append(document.body, {tag: 'div'}); // create elDefaultDialog.superclass.constructor.call(this, el, config); // run superclass
}; Ext.extend(DefaultDialog, Ext.BasicDialog); // DefaultDialog extends Ext.BasicDialog
DefaultDialog example
• We can now re-use the DefaultDialog class • By passing configuration options we can override the defaults• By omitting the configuration, we assume the defaults dlg = new DefaultDialog({title: 'First Dialog', width: 300}); dlg.show(); dlg2 = new DefaultDialog(); dlg2.show();
ExtJS Events
Events
• Events describe when a certain action happens. This could be a user action, a response to an Ajax call, etc.
• Events also provide us with some information about what occurred via arguments
Events• The DOM model describes numerous events which
may occur to an HTMLElement.• Such as:
– mousedown– mouseover– click– select– blur– focus– change
• http://www.w3.org/TR/DOM-Level-2-Events/events.html
Event Registration
• Please avoid DOM level 0 event registration by NOT placing your event handlers in-line<a href=“” onclick=“return myFunction()”>link</a>
• Event handling like this has been deprecated for some time and using it in dynamic applications may cause memory leaks!
Event-handling
• ExtJS normalizes event-handling differences across the browsers.
• To add an event handler to an event we use the following syntax.Ext.fly(‘myElement’).on(‘click’, myFunction, scope);
• To remove an event handler to an event we use the following syntax.Ext.fly(‘myElement’).un(‘click’, myFunction, scope);
Event handling
• When using Ext.Element all standard HTMLElement events are exposed.
• The called function will receive 2 arguments.– event – This is Ext.EventObject which normalizes
event information cross-browser– target – This is an HTMLElement which desribes
the target which was clicked.
Events
• All classes which expose events inherit from Ext.util.Observable.
• Observable is a design pattern which allows a subject object to notify zero to many subscriber objects
• The subscribers are not guaranteed to be called in any order
http://en.wikipedia.org/wiki/Observer_pattern
Events
• Events tell their subscribers about when and what happened.
• Subscribers can react appropriately without knowing why an event occurred.
• Refer to the ExtJS Documentation when you want to know what arguments you will be passed.– (Click Events link at the top of each class)
Example ExtJS Docs
• complete• public event complete • Fires after editing is complete and any changed value
has been written to the underlying field. Subscribers will be called with the following parameters: – this : Editor– value : Mixed The current field value– startValue : Mixed The original field value
• This event is defined by Editor.
this.editItemNumber.on('complete', this.commitRecord, this);
commitRecord : function(ed, value, oldValue) {var boundElDom = ed.boundEl.dom;var recordId = boundElDom.parentNode.id;var currRecord = this.store.getById(recordId);var cn = boundElDom.className;currRecord.set(cn, value);currRecord.commit();this.refresh();
},
ExtJS Events
• Many ExtJS classes expose before events which will allow you to cancel an action by returning false.
• Ex:ds.on(‘beforeload’, function(ds, opts) {return false;});
• In a real situation we would make an intelligent decision given ds and opts to cancel the load event.
REFERENCES AND LINKS:
• Main Websitehttp://www.sencha.com/
• Learning EXT JShttp://www.sencha.com/learn/Ext_Getting_Started
• EXT JS Downloadhttp://www.sencha.com/products/extjs/download/
• EXT JS API Documentation http://dev.sencha.com/deploy/dev/docs/
• EXT JS Sampleshttp://dev.sencha.com/deploy/dev/examples/