Extjs

30,675 views
30,508 views

Published on

Published in: Technology

Extjs

  1. 1. 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. 2. 2 Module 1(Day1): JavaScript The 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
  3. 3. Module 2 (Day2): ExtJs • Introduction of ExtJs • Getting Started • Fundamental Classes • Event Handling • Component Model • Examples
  4. 4. Module 3 (Day3): ExtJs cont… • Getting Started with Sencha Architect • Create and Configure Components • Create/Configure Data Stores • Templates & DataView • Creating & Extending Classes • Examples
  5. 5. Module 4 (Day4): ExtJs cont… • Internationalization • Drag & Drop • Hands-on Experience w/ Common Components • TabPanel • GridPanel • TreePanel • FormPanelBuilding a Theme • Application Best Practices
  6. 6. 6 Objectives At the end of this module you will be able to: 1. Write JavaScript code using all the basic elements of JavaScript Programs 2. Create Windows & Dialog Boxes 3. Use the JavaScript’s in-built objects in a web page 4. Write code that does Event Handling in HTML pages 5. Manipulate HTML Forms through JavaScript dynamically 6. Integrate Java and JavaScript through Applets
  7. 7. 7 DHTML DHTML stands for Dynamic Hyper Text Markup Language which helps to add Dynamic content to static HTML pages.
  8. 8. 8 Introduction to JavaScript JavaScript is: 1. An easy to use object scripting language 2. Designed for creating live online applications 3. Code is included as part of a HTML document 4. Scripts are run by the Web browser
  9. 9. 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. 10. 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. 11. 11 Elements of JavaScript Program Elements of JavaScript Program can be divided into five categories, as follows: 1. Variables 2. Expressions 3. Control Structures 4. Functions 5. Objects and Arrays
  12. 12. 12 Elements of JavaScript Program: Variables • Data Types • Rules for variable names • Type Casting • Variable Declaration and Scope
  13. 13. 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 }
  14. 14. 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 ; }
  15. 15. 20 Objects • An object is a self-contained unit of code having the following characteristics: – Properties – Methods – Identity
  16. 16. 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()
  17. 17. 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)
  18. 18. 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
  19. 19. 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
  20. 20. 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
  21. 21. 26 Objects: The String Object • Any String variable in JavaScript is a String object. It has a property – Length and – Many Methods
  22. 22. 27 Objects: The Date Object • Is built-in JavaScript object • Create using new keyword
  23. 23. 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.
  24. 24. 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.
  25. 25. 32 Arrays • JavaScript doesn’t support array variables • Arrays need to be created using array object
  26. 26. 33 Events • Are things that happen to the browser • Used to trigger portions of program • Pertain to the web page containing the script
  27. 27. 34 Events: Event Handlers • Embedded in HTML tags as part of anchor and links or any of the form element tags.
  28. 28. 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
  29. 29. 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
  30. 30. 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
  31. 31. 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
  32. 32. 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';">
  33. 33. 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
  34. 34. 41 Events and event handlers II Event Applies to Occurs when Handler 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
  35. 35. 42 Events and event handlers III Event Applies to Occurs when Handler 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
  36. 36. 43 Events and event handlers IV Event Applies to Occurs when Handler 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
  37. 37. 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
  38. 38. 45 Events and event handlers VI Event Applies to Occurs when Handler 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
  39. 39. 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
  40. 40. JavaScript and HTML Forms • window [closed, location] – history [length] – document [bgColor, fgColor, URL, lastmodified,linkColor, vlinkColor] » images [properties] » links [properties] » frames [properties] » forms [properties]
  41. 41. 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
  42. 42. 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>
  43. 43. 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
  44. 44. 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>
  45. 45. 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>
  46. 46. 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
  47. 47. JavaScript and HTML Forms InteractiveProgrammingontheInternet ,Knuckles
  48. 48. 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>
  49. 49. JavaScript and HTML Forms Form for submitting info for server side processing InteractiveProgrammingonthe Internet,Knuckles
  50. 50. 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>
  51. 51. 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
  52. 52. 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
  53. 53. Introduction to ExtJS Framework
  54. 54. 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.
  55. 55. • 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
  56. 56. WHY EXT JS ? • This is really what matters (MVC) o Easy Client-side data modeling  Relational Models o Simple to use GUI widgets
  57. 57. Why we use Extjs? • The chart below shows statistics of distribution 10 most popular JS Libraries
  58. 58. Why we use Extjs? • The chart below shows statistics of distribution 10 most popular JS Libraries Where is Extjs on this chart?
  59. 59. 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%
  60. 60. MVC • Why is MVC so important? o In this case, it is because it is 100%, agent-based, client side code o This means typical MVC on the server is not needed  Good or Bad? Design decision
  61. 61. Server Side MVC
  62. 62. Server Side Models • Server Side Models are simple classes that house an 'instantiated' version of a resource record o 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
  63. 63. 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 resource o "Select `id`, `first`, `last` from `names`...... • The model would then have member variables: o $model->id o $model->first o $model->last o ....
  64. 64. Server Side Models • All of my models have key features o 1-to-1 resource mapping o $model->save() o $model->find() o $model->delete() • Similar to CRUD operations except I leave save() to determine wether it is Create or Update o CRUD === 'Create Read Update Destroy'
  65. 65. Server Side Views • Sever Side View classes, for most frameworks, take the model data and return the requested type of view o 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 fault o What happens when I want to use this server side stack for mobile apps? • Are there any performance flaws?
  66. 66. Server Side Control • We have seen that how models and views work o 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?
  67. 67. 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 possible o This allows for powerful client machines to do most of our processing and rendering o Only allow the client to manipulate data that can be considered hostile!
  68. 68. ExtJS Models • The most important feature of ExtJS o Can have relational models!!!!!!! o Example:  Orders (a model) can have many Order Items (another model) o Each record of orders is stored in store o Each record of orders points to another store that has its Order items o This allows us to select an order, and then immediately have access to all its order items
  69. 69. ExtJS View • Since this is JavaScript, we immediately expect robust GUI widgets • Of course, you can add CSS and style them
  70. 70. ExtJS Control • JavaScript is a functional language o This allows for very strong and very easy control logic o Of course, you can still use OOP style if desired
  71. 71. So how does this all work? • By using MVC on the client side: o We only need to contact the server when using CRUD operations o By control logic when otherwise needed • Lets go through an example
  72. 72. EXT Windows looks like OS windows – support dragging/resizing/closing
  73. 73. Good Documentation
  74. 74. EXT JS SAMPLES
  75. 75. Community Support
  76. 76. Cross Browser
  77. 77. Adapters
  78. 78. Commercial and Open Source License
  79. 79. WIDGETS PROVIDED BY EXTJS
  80. 80. WINDOW
  81. 81. Combobox
  82. 82. Data grid sort columns editable data source
  83. 83. CHART
  84. 84. CALENDAR
  85. 85. Getting Started
  86. 86. Download: http://sencha.com/products/extjs/do wnload.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.
  87. 87. 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. 31/01/2015 111 Beginning ExtJS with ASP.NET - Lesson 01 - Part two
  88. 88. 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 ) 31/01/2015 112 Beginning ExtJS with ASP.NET - Lesson 01 - Part two
  89. 89. 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>
  90. 90. 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.
  91. 91. EXAMPLE OF HELLO WORLD ALERT WINDOW
  92. 92. Hello World
  93. 93. RESULT
  94. 94. EXAMPLE OF CREATING TABS
  95. 95. HTML CODE
  96. 96. JS CODE
  97. 97. RESULT:
  98. 98. 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 }); }); 31/01/2015 123
  99. 99. Hello World with ExtJS… Eureka!!!, there we go…  31/01/2015 124
  100. 100. A close look at our code & output Our 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. 31/01/2015 125
  101. 101. 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. 31/01/2015 126 Beginning ExtJS with ASP.NET - Lesson 01 - Part two
  102. 102. 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. 31/01/2015 127
  103. 103. 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 31/01/2015 128
  104. 104. 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. 31/01/2015 129
  105. 105. When Ext.onReady() fires? Client browser Web Server ASP.Net Life Cycle Parsed contents Browser generates the page On after generation, Ext.onReady() fires 1 2 3 6 5 4 130
  106. 106. 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. 31/01/2015 131
  107. 107. 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. 31/01/2015 132
  108. 108. 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. 31/01/2015 133
  109. 109. 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. 31/01/2015 134
  110. 110. What else extjs can do? • Ajax support • Dom traversing • Dom manipulation • Event Handling • Selectors • OOP emulation • Animation
  111. 111. Main extjs classes • Component • Panel • Observable • Store
  112. 112. 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())
  113. 113. 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
  114. 114. 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
  115. 115. 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
  116. 116. ExtJS Classes
  117. 117. 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’});
  118. 118. 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);
  119. 119. 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.
  120. 120. 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)
  121. 121. 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);
  122. 122. 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)
  123. 123. 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.
  124. 124. 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
  125. 125. 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. ...
  126. 126. Example • This is an example, where an unordered list with 3 children items is appended to an existing element with id 'my-div':
  127. 127. 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);
  128. 128. 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);
  129. 129. 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.
  130. 130. 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);
  131. 131. 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
  132. 132. 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 property var el = Ext.DomHelper.append(document.body, {tag: 'div'}); // create el DefaultDialog.superclass.constructor.call(this, el, config); // run superclass }; Ext.extend(DefaultDialog, Ext.BasicDialog); // DefaultDialog extends Ext.BasicDialog
  133. 133. 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();
  134. 134. ExtJS Events
  135. 135. 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
  136. 136. 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
  137. 137. 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!
  138. 138. 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);
  139. 139. 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.
  140. 140. 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
  141. 141. 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)
  142. 142. 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.
  143. 143. 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(); },
  144. 144. 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.
  145. 145. REFERENCES AND LINKS: • Main Website http://www.sencha.com/ • Learning EXT JS http://www.sencha.com/learn/Ext_Getting_Started • EXT JS Download http://www.sencha.com/products/extjs/download/ • EXT JS API Documentation http://dev.sencha.com/deploy/dev/docs/ • EXT JS Samples http://dev.sencha.com/deploy/dev/examples/
  146. 146. 31-01-2015171 Girish Srivastava girish092.ch@gmail.com

×