Sencha [ExtJS]: Object Oriented JavaScriptRohan Chandanewww.slideshare.net/rohan.chandane
NamespaceClassConstructorPropertiesMethods/ FunctionsObjectInheritanceObject Oriented Approach
Defining a namespace in Sencha (ExtJS) classgives unique name for the JavaScript Classhelps in organizing JavaScript codedeclaring namespace in ExtJS/ SenchaegExt.ns("com.company.app");Namespace
Two ways to write custom class in ExtJS1st wayClassExt.ns("com.company.app");(function(){       // class definition    var JSClass = Ext.extend(Object,{    .    .    })// end of class definition     com.company.app.JSClass = JSClass;})();
2nd wayContinued.. var com.company.app.JSClass = Ext.extend(Object,{    .    . })// end of class definition
ConstructorExt.ns("com.company.app");(function(){    varJSClass = Ext.extend(Object,{        //constructor function, this function will get 	         	//execute when object is created for the class    	constructor: function(config){        	//console.log("JSClass constructor");        	Ext.apply(this, config)    	}    .    .    })    com.company.app.JSClass = JSClass ;})();
Constructor, function, attributeExt.ns("com.company.app");(function(){    var JSClass = Ext.extend(Object,{        //constructor function        constructor: function(config){            //console.log("constructor called" );            Ext.apply(this, config)        },    	// attribute    	color: 'red',    	// some function    	moveBlock: function(newX, newY, myDiv1){        	    Ext.get(myDiv1).moveTo(newX, newY, true);	}    	.    })    com.company.app.JSClass = JSClass;})();
Create Object & Call a function// it need to include file JSClass.js in HTML, if it's // calling from HTML// create a object of the classvarobj = new com.company.app.JSClass();obj.moveBlock('0','-250','searchDiv');
InheritanceExt.ns("com.company.app");(function(){    varNewJSClass = Ext.extend(com.company.app.JSClass,{    .    .    .    })    com.company.app.NewJSClass = NewJSClass;})();
Using extended classExt.ns("com.company.app");(function(){    varNewJSClass = Ext.extend(com.company.app.JSClass ,{        color: 'blue',        constructor: function(config){            JSClass.superclass.constructor.apply(this, arguments)        },        // method override        moveBlock: function(newY, myDiv1){            Ext.get(myDiv1).moveTo(0, newY, true);        }    })    com.company.app.NewJSClass = NewJSClass;})();
Module Pattern: POJO like classExt.ns("com.company.app");(function(){    var JSClass = Ext.extend(Object,{        //constructor function    constructor: function(config){        Ext.apply(this, config)    }    // class variable    ,value1: null    ,value2: null    	// getter, setter    ,getValue1:function(){        return value1;    }    ,setValue1: function(val){        this.value1 = val;    }          })    com.company.app.JSClass = JSClass;})();
Ext.apply simply copies data members from a source object to a destination object and allows you to provide default valuesDefaults are optional, when there is defaults it does thisRun the next example in firebug, to understand it quicklyExt.apply()Syntax:Ext.apply(receivingObject, sendingObject, defaults)Ext.apply(receivingObject, defaults);Ext.apply(receivingObject, sendingObject);
Continued..var obj1 = {firstName: 'Rohan', lastName: 'Chandane'}console.log(obj1)//{firstName: 'Rohan', lastName: 'Chandane'}var obj2 = {job:'Dev', lang:'JavaScript', c: function(){}}console.log(obj2)// {job:'Dev', lang:'JavaScript' c: function(){}}var obj3 = Ext.apply(obj2, obj1, {newVar: 'new value'})console.log(obj3)// {firstName: 'Rohan', lastName: 'Chandane', job:'Dev', lang:'JavaScript' c: function(){}, newVar: 'new value'}// replacing job value herevar obj3 = Ext.apply(obj2, obj1, {job: 'new value'})console.log(obj3)// {firstName: 'Rohan', lastName: 'Chandane', job:'new value', lang:'JavaScript' c: function(){}}
Then what is the difference between Ext.apply() and Ext.extend()Ext.extend will inherit a superclass's data members and methods as well as add a superclass property and an override method.Ext.apply simply copies data membersContinued..
Modifying constructor in Module pattern to check Ext.apply()Adding console.log in JSClassto print configCreate object of JSClassclassContinued..constructor: function(config){Ext.apply(this, config);    console.log(this.newVar)}// creating object of JSClass (Module Pattern)var config = {varnewVar = “Rohan”}varnewObj = com.company.app.JSClass(config);// Rohan
Extras of OO JavaScript
JavaScript is dynamic object oriented languageProperties and Function can be added and removed at run timeFunction can be moved from one object to anotherExample:Continued..varobj = new Object();propertyName="firstName";propertyValue="Rohan";console.log(obj.firstName);// undefinedeval("obj ."+propertyName+"='"+propertyValue+"'");console.log(obj.firstName);// Rohandelete (obj.firstName)console.log(obj.firstName)// undefined
Basic Project Setup
Ajax application can be divided in two partAjax DeluxeApplications feel similar to a desktop appIts fully Ajax + JavaScript driven applicationScalable and for big applications Ajax LiteApplication/website feels more like a conventional web appAjax is used for small operations like validation with serverUseful only for small, quick functionalityWeb 2 App types
Here, lets take a look at Ajax Deluxe first Continued..
Project structureAppName||_lib|   |_com|   |   |_company|   |       |_myapp|   |            |_package1|   |                |_Main.js |   |            |_package2|   |_ext|       |_(Extracted ExtJS lib & folders)|       |_(...)||_assets|   |_css|   |_img||_Index.html
Index.htmlVersion 1:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html xmlns="http://www.w3.org/1999/xhtml">    <head>      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">    <title>Basic Setup</title>    <!-- Bring in the ExtJs Libraries and CSS -->    <link rel="stylesheet" type="text/css" href="lib/ext/resources/css/ext-all.css"/>    <script type="text/javascript" src="lib/ext/adapter/ext/ext-base.js"></script>    <script type="text/javascript" src="lib/ext/ext-all.js"></script>          <!-- Place the page specific js here -->       <script type="text/javascript">             Ext.onReady(function(){            // Mandatory: need to add this spacer            Ext.BLANK_IMAGE_URL = 'lib/ext/resources/images/default/s.gif';            // alert message box to check if ExtJS loaded            Ext.MessageBox.alert("Hello Example","Hello, Rohan! ExtJS loaded successfully!");        });       </script>        </head>    <body></body></html>
Index.htmlVersion 2:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html xmlns="http://www.w3.org/1999/xhtml">    <head>      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">    <title>Basic Setup</title>    <!-- Bring in the ExtJs Libraries and CSS -->    <link rel="stylesheet" type="text/css" href="lib/ext/resources/css/ext-all.css"/>    <script type="text/javascript" src="lib/ext/adapter/ext/ext-base.js"></script>    <script type="text/javascript" src="lib/ext/ext-all.js"></script>          <!-- Place the page specific js here -->    <script type="text/javascript" src="lib/com/company/myapp/package1/Main.js "> </script>        </head>    <body></body></html>
Main.js Version 2:Ext.onReady(function(){    // Mandatory: need to add this spacer /*[relative path to..]*/    Ext.BLANK_IMAGE_URL = ‘lib/ext/resources/images/default/s.gif';    Ext.QuickTips.init();    // alert message box to check if ExtJS loaded    Ext.MessageBox.alert("Hello Example","Hello, Rohan! ExtJS loaded successfully!");});
Now, for creating a Ajax Deluxe App from our existing setupIt needs to use Border Layout (Viewport)We will edit Main.js and will add Ext.Viewport()As border layout has north, south, west, east & center region, We will add those using Ext.Panel()So Main.js will look like this -Continued..
Main.js with Ext.Viewport()Ext.onReady(function(){    // Mandatory: need to add this spacer /*[relative path to..]*/Ext.BLANK_IMAGE_URL = 'lib/ext/resources/images/default/s.gif';Ext.QuickTips.init();    // viewport panels varnorthPanel = new Ext.Panel({	id: 'north-panel', height : 50,region: 'north', border: false, title:'Top Panel'});varsouthPanel = new Ext.Panel({	id: 'south-panel', height : 200, region: 'south', title : 'South Panel', 	collapsible: true, collapsed: true});varwestPanel = new Ext.Panel({     	id: 'west-panel', layout: 'fit', width: 250, region: 'west', title: 	'Navigation', collapsible: true     });varcenterPanel = new Ext.Panel({     	region: 'center' ,layout: 'fit', title: 'Content Panel'     });// viewportnew Ext.Viewport({id: 'id-viewport'    ,layout : 'border'    ,items  : [northPanel,southPanel,westPanel,centerPanel]});});
Preview: using Viewport
Here is object oriented programming with JavaScriptWe will create View, ViewLayout.js Class, which will render this Border Layout.We will modify Main.js and will create ViewLayout.js in directory package2Add entry in Index.html for ViewLayout.js, Main.jsOO
Index.html<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">    <title>Basic Setup</title>    <!-- Bring in the ExtJs Libraries and CSS -->    <link rel="stylesheet" type="text/css" href="lib/ext/resources/css/ext-all.css"/>    <script type="text/javascript" src="lib/ext/adapter/ext/ext-base.js"></script>    <script type="text/javascript" src="lib/ext/ext-all.js"></script>   <!-- Place the page specific js here --><script type="text/javascript" src="lib/com/company/hello/package2/Main.js"></script>   <script type="text/javascript" src="lib/com/company/hello/package2/ViewLayout.js"> </script></head>
ViewLayout.jsExt.ns("com.company.hello.package2");(function(){varViewLayout = Ext.extend(Object,{        constructor: function(config){Ext.apply(this, config);        },        // creating page layout, code goes here        /* public */ createLayout: function(){        // viewport panels varnorthPanel = new Ext.Panel({	id: 'north-panel', height : 50,region: 'north', border: false, title:‘ Top Panel'});varsouthPanel = new Ext.Panel({	id: 'south-panel', height : 200, region: 'south', title : 'South Panel', collapsible: true, collapsed: true   });varwestPanel = new Ext.Panel({	id: 'west-panel', layout: 'fit', width: 250, region: 'west', title: 'Navigation',    collapsible: true   });varcenterPanel = new Ext.Panel({	region: 'center' ,layout: 'fit', title: 'Content Panel'});code continues..
Continued..        // viewport        new Ext.Viewport({            id: 'id-viewport'            ,layout : 'border'            ,items  : [northPanel, southPanel, westPanel, centerPanel]        });}    });    com.company.hello.package2.ViewLayout = ViewLayout;})();
Main.jsExt.onReady(function(){    // Mandatory: need to add this spacer /*[relative path to..]*/Ext.BLANK_IMAGE_URL = 'lib/ext/resources/images/default/s.gif';Ext.QuickTips.init();    // main execution start here, user defined functionvaronModuleLoad = function(){varviewLayout = new com.company.hello.package2.ViewLayout();viewLayout.createLayout();        }    // main starting pointonModuleLoad();});
Preview: using OO, ViewPort
Design Patterns with ExtJS
SingletonExt.ns("com.netapp.hello.package1");	(function() {varSingletonModel = Ext.extend(Object, {			_instance : null		,constructor : function() {			console.log("Singleton constructor called : " + this.getInstance());		}		,getInstance : function() {			if (this._instance === null) {this._instance = this.createInstance();			}			return this._instance;		}		,createInstance : function() {			return 10;		}	});	com.netapp.hello.package1.SingletonModel = SingletonModel;})()
ModuleExt.ns("com.netapp.hello.package1");	(function(){varModulePattern = Ext.extend(Object,{name:"Rohan"		,constructor:function(){			console.log("constrcutor");		},getName:function(){			this.name;		},setName:function(val){			this.name = val;		}	});	com.netapp.hello.package2.ModulePattern = ModulePattern;})()
Performance with ExtJS
Use reusable code Object Oriented Approach Modularize codeDo not access DOM frequentlyIts computational heavy codeUse Lazy loading, wherever possibleBut avoid heavy nesting Use of event delegationEvents should be assigned to a smaller subset of the document/element, rather than each individual element, this uses JavaScript’s event bubbling notion.  this approach takes less memory in browserContinued..
Use of JavaScript minification, obfuscaterYUI compressor, Linters  (jsonlint.com, jslint.com)Use of efficient programming practices in JavaScript Example: String manipulation - instead of string concatenation using ‘+’ operator, use of array’s .join() function, this way it will be better garbage collected.Cross Browser Scripting: using web standards, feature detection techniques instead browser detection technique and browser specific codeRemove listeners which are not in use anymoreContinued..
Loops are heavy, it can be optimized by using simple techniquesIn for loop, whenever reading length of array, store it in some variable instead of reading it again and again using array.lengthAvoid creating lot of HTML code with JavaScriptContinued..
I will update these notes periodically with my experiments, stay tuned..Note
Referenceshttp://www.jslog.comhttp://ajaxpatterns.orghttp://www.sencha.com/forum/http://edspencer.nethttp://code.google.com/p/v8/http://www.cherny.com/

More Related Content

PPT
ExtJs Basic Part-1
PPTX
Sencha ExtJs Learning Part 2 - MVC And MVVM Architecture in ExtJs [ENGLISH]
PPTX
Sencha ExtJs Learning Part 1 - Layout And Container in Sencha ExtJs - By Irfa...
PDF
How AngularJS Embraced Traditional Design Patterns
PPTX
Basics of Ext JS
ODP
Angularjs
PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
ExtJs Basic Part-1
Sencha ExtJs Learning Part 2 - MVC And MVVM Architecture in ExtJs [ENGLISH]
Sencha ExtJs Learning Part 1 - Layout And Container in Sencha ExtJs - By Irfa...
How AngularJS Embraced Traditional Design Patterns
Basics of Ext JS
Angularjs
Intro To JavaScript Unit Testing - Ran Mizrahi

What's hot (20)

PPT
Learn javascript easy steps
PDF
Speed up your Web applications with HTML5 WebSockets
PDF
RequireJS & Handlebars
PDF
Javascript Best Practices
PDF
Page Object Model and Implementation in Selenium
PDF
JavaScript Modules Done Right
PPT
AspMVC4 start101
PPTX
AngularJs presentation
PDF
Django design-patterns
PDF
JavaScript 101
PDF
Rails Best Practices
PPT
Java Server Faces (JSF) - advanced
PDF
Java script tutorial
ODP
Session 2- day 3
PDF
Seven Versions of One Web Application
PPTX
Wt unit 4
ODP
Jquery- One slide completing all JQuery
PPTX
Developing components and extensions for ext js
PPTX
Wt unit 3
Learn javascript easy steps
Speed up your Web applications with HTML5 WebSockets
RequireJS & Handlebars
Javascript Best Practices
Page Object Model and Implementation in Selenium
JavaScript Modules Done Right
AspMVC4 start101
AngularJs presentation
Django design-patterns
JavaScript 101
Rails Best Practices
Java Server Faces (JSF) - advanced
Java script tutorial
Session 2- day 3
Seven Versions of One Web Application
Wt unit 4
Jquery- One slide completing all JQuery
Developing components and extensions for ext js
Wt unit 3
Ad

Similar to Sencha / ExtJS : Object Oriented JavaScript (20)

PPTX
Extension Javascript
PPTX
Ext JS Introduction
PPT
Ext Js
ODP
ExtJS framework
PPT
Silicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NET
PPTX
Sencha Touch - Introduction
PDF
Four Ways to add Features to Ext JS
PPTX
Building Rich Internet Applications with Ext JS
PDF
Aprimorando sua Aplicação com Ext JS 4 - BrazilJS
PPTX
Ext JS Architecture Best Practices - Mitchell Simeons
PPTX
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
PPT
Ext oo
PPTX
Ext Js introduction and new features in Ext Js 6
PPTX
Introduction to ExtJS and its new features
PPTX
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
PPT
Introduction to ExtJS
PDF
dojo.Patterns
PPTX
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
PDF
ExtJS: La piattaforma vincente (class system)
PDF
Building a Mobile App with Sencha Touch
Extension Javascript
Ext JS Introduction
Ext Js
ExtJS framework
Silicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NET
Sencha Touch - Introduction
Four Ways to add Features to Ext JS
Building Rich Internet Applications with Ext JS
Aprimorando sua Aplicação com Ext JS 4 - BrazilJS
Ext JS Architecture Best Practices - Mitchell Simeons
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
Ext oo
Ext Js introduction and new features in Ext Js 6
Introduction to ExtJS and its new features
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
Introduction to ExtJS
dojo.Patterns
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
ExtJS: La piattaforma vincente (class system)
Building a Mobile App with Sencha Touch
Ad

More from Rohan Chandane (13)

PDF
Agile Maturity Model, Certified Scrum Master!
PDF
Agile & Scrum, Certified Scrum Master! Crash Course
PDF
An Introduction To Testing In AngularJS Applications
PDF
Agile :what i learnt so far
PDF
Backbone js
PDF
PDF
TIBCO General Interface - CSS Guide
PDF
Blogger's Park Presentation (Blogging)
PDF
J2ME GUI Programming
PDF
Parsing XML in J2ME
PDF
J2ME RMS
PDF
J2ME IO Classes
PDF
Java2 MicroEdition-J2ME
Agile Maturity Model, Certified Scrum Master!
Agile & Scrum, Certified Scrum Master! Crash Course
An Introduction To Testing In AngularJS Applications
Agile :what i learnt so far
Backbone js
TIBCO General Interface - CSS Guide
Blogger's Park Presentation (Blogging)
J2ME GUI Programming
Parsing XML in J2ME
J2ME RMS
J2ME IO Classes
Java2 MicroEdition-J2ME

Recently uploaded (20)

DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PDF
Complications of Minimal Access-Surgery.pdf
PDF
Empowerment Technology for Senior High School Guide
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
My India Quiz Book_20210205121199924.pdf
PDF
Uderstanding digital marketing and marketing stratergie for engaging the digi...
PPTX
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
PDF
AI-driven educational solutions for real-life interventions in the Philippine...
PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
Cambridge-Practice-Tests-for-IELTS-12.docx
Complications of Minimal Access-Surgery.pdf
Empowerment Technology for Senior High School Guide
Paper A Mock Exam 9_ Attempt review.pdf.
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
Share_Module_2_Power_conflict_and_negotiation.pptx
What if we spent less time fighting change, and more time building what’s rig...
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
My India Quiz Book_20210205121199924.pdf
Uderstanding digital marketing and marketing stratergie for engaging the digi...
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
AI-driven educational solutions for real-life interventions in the Philippine...
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
Practical Manual AGRO-233 Principles and Practices of Natural Farming
Environmental Education MCQ BD2EE - Share Source.pdf
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Chinmaya Tiranga quiz Grand Finale.pdf

Sencha / ExtJS : Object Oriented JavaScript

  • 1. Sencha [ExtJS]: Object Oriented JavaScriptRohan Chandanewww.slideshare.net/rohan.chandane
  • 3. Defining a namespace in Sencha (ExtJS) classgives unique name for the JavaScript Classhelps in organizing JavaScript codedeclaring namespace in ExtJS/ SenchaegExt.ns("com.company.app");Namespace
  • 4. Two ways to write custom class in ExtJS1st wayClassExt.ns("com.company.app");(function(){   // class definition    var JSClass = Ext.extend(Object,{    .    .    })// end of class definition     com.company.app.JSClass = JSClass;})();
  • 5. 2nd wayContinued.. var com.company.app.JSClass = Ext.extend(Object,{    .    . })// end of class definition
  • 6. ConstructorExt.ns("com.company.app");(function(){    varJSClass = Ext.extend(Object,{        //constructor function, this function will get //execute when object is created for the class     constructor: function(config){         //console.log("JSClass constructor");         Ext.apply(this, config)     }    .    .    })    com.company.app.JSClass = JSClass ;})();
  • 7. Constructor, function, attributeExt.ns("com.company.app");(function(){    var JSClass = Ext.extend(Object,{        //constructor function     constructor: function(config){         //console.log("constructor called" );         Ext.apply(this, config)     },     // attribute     color: 'red',     // some function     moveBlock: function(newX, newY, myDiv1){         Ext.get(myDiv1).moveTo(newX, newY, true); }     .    })    com.company.app.JSClass = JSClass;})();
  • 8. Create Object & Call a function// it need to include file JSClass.js in HTML, if it's // calling from HTML// create a object of the classvarobj = new com.company.app.JSClass();obj.moveBlock('0','-250','searchDiv');
  • 9. InheritanceExt.ns("com.company.app");(function(){    varNewJSClass = Ext.extend(com.company.app.JSClass,{    .    .    .    })    com.company.app.NewJSClass = NewJSClass;})();
  • 10. Using extended classExt.ns("com.company.app");(function(){    varNewJSClass = Ext.extend(com.company.app.JSClass ,{        color: 'blue',        constructor: function(config){            JSClass.superclass.constructor.apply(this, arguments)        },        // method override        moveBlock: function(newY, myDiv1){            Ext.get(myDiv1).moveTo(0, newY, true);        }    })    com.company.app.NewJSClass = NewJSClass;})();
  • 11. Module Pattern: POJO like classExt.ns("com.company.app");(function(){    var JSClass = Ext.extend(Object,{        //constructor function    constructor: function(config){        Ext.apply(this, config)    }    // class variable    ,value1: null    ,value2: null     // getter, setter    ,getValue1:function(){     return value1;    }    ,setValue1: function(val){     this.value1 = val;    }          })    com.company.app.JSClass = JSClass;})();
  • 12. Ext.apply simply copies data members from a source object to a destination object and allows you to provide default valuesDefaults are optional, when there is defaults it does thisRun the next example in firebug, to understand it quicklyExt.apply()Syntax:Ext.apply(receivingObject, sendingObject, defaults)Ext.apply(receivingObject, defaults);Ext.apply(receivingObject, sendingObject);
  • 13. Continued..var obj1 = {firstName: 'Rohan', lastName: 'Chandane'}console.log(obj1)//{firstName: 'Rohan', lastName: 'Chandane'}var obj2 = {job:'Dev', lang:'JavaScript', c: function(){}}console.log(obj2)// {job:'Dev', lang:'JavaScript' c: function(){}}var obj3 = Ext.apply(obj2, obj1, {newVar: 'new value'})console.log(obj3)// {firstName: 'Rohan', lastName: 'Chandane', job:'Dev', lang:'JavaScript' c: function(){}, newVar: 'new value'}// replacing job value herevar obj3 = Ext.apply(obj2, obj1, {job: 'new value'})console.log(obj3)// {firstName: 'Rohan', lastName: 'Chandane', job:'new value', lang:'JavaScript' c: function(){}}
  • 14. Then what is the difference between Ext.apply() and Ext.extend()Ext.extend will inherit a superclass's data members and methods as well as add a superclass property and an override method.Ext.apply simply copies data membersContinued..
  • 15. Modifying constructor in Module pattern to check Ext.apply()Adding console.log in JSClassto print configCreate object of JSClassclassContinued..constructor: function(config){Ext.apply(this, config); console.log(this.newVar)}// creating object of JSClass (Module Pattern)var config = {varnewVar = “Rohan”}varnewObj = com.company.app.JSClass(config);// Rohan
  • 16. Extras of OO JavaScript
  • 17. JavaScript is dynamic object oriented languageProperties and Function can be added and removed at run timeFunction can be moved from one object to anotherExample:Continued..varobj = new Object();propertyName="firstName";propertyValue="Rohan";console.log(obj.firstName);// undefinedeval("obj ."+propertyName+"='"+propertyValue+"'");console.log(obj.firstName);// Rohandelete (obj.firstName)console.log(obj.firstName)// undefined
  • 19. Ajax application can be divided in two partAjax DeluxeApplications feel similar to a desktop appIts fully Ajax + JavaScript driven applicationScalable and for big applications Ajax LiteApplication/website feels more like a conventional web appAjax is used for small operations like validation with serverUseful only for small, quick functionalityWeb 2 App types
  • 20. Here, lets take a look at Ajax Deluxe first Continued..
  • 21. Project structureAppName||_lib|   |_com|   |   |_company|   |       |_myapp|   |            |_package1|   |                |_Main.js |   |            |_package2|   |_ext|       |_(Extracted ExtJS lib & folders)|       |_(...)||_assets|   |_css|   |_img||_Index.html
  • 22. Index.htmlVersion 1:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html xmlns="http://www.w3.org/1999/xhtml">    <head>      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">    <title>Basic Setup</title>    <!-- Bring in the ExtJs Libraries and CSS -->    <link rel="stylesheet" type="text/css" href="lib/ext/resources/css/ext-all.css"/>    <script type="text/javascript" src="lib/ext/adapter/ext/ext-base.js"></script>    <script type="text/javascript" src="lib/ext/ext-all.js"></script>          <!-- Place the page specific js here -->       <script type="text/javascript">             Ext.onReady(function(){            // Mandatory: need to add this spacer            Ext.BLANK_IMAGE_URL = 'lib/ext/resources/images/default/s.gif';            // alert message box to check if ExtJS loaded            Ext.MessageBox.alert("Hello Example","Hello, Rohan! ExtJS loaded successfully!");        });     </script>        </head>    <body></body></html>
  • 23. Index.htmlVersion 2:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html xmlns="http://www.w3.org/1999/xhtml">    <head>      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">    <title>Basic Setup</title>    <!-- Bring in the ExtJs Libraries and CSS -->    <link rel="stylesheet" type="text/css" href="lib/ext/resources/css/ext-all.css"/>    <script type="text/javascript" src="lib/ext/adapter/ext/ext-base.js"></script>    <script type="text/javascript" src="lib/ext/ext-all.js"></script>          <!-- Place the page specific js here -->    <script type="text/javascript" src="lib/com/company/myapp/package1/Main.js "> </script>        </head>    <body></body></html>
  • 24. Main.js Version 2:Ext.onReady(function(){    // Mandatory: need to add this spacer /*[relative path to..]*/    Ext.BLANK_IMAGE_URL = ‘lib/ext/resources/images/default/s.gif';    Ext.QuickTips.init();    // alert message box to check if ExtJS loaded    Ext.MessageBox.alert("Hello Example","Hello, Rohan! ExtJS loaded successfully!");});
  • 25. Now, for creating a Ajax Deluxe App from our existing setupIt needs to use Border Layout (Viewport)We will edit Main.js and will add Ext.Viewport()As border layout has north, south, west, east & center region, We will add those using Ext.Panel()So Main.js will look like this -Continued..
  • 26. Main.js with Ext.Viewport()Ext.onReady(function(){ // Mandatory: need to add this spacer /*[relative path to..]*/Ext.BLANK_IMAGE_URL = 'lib/ext/resources/images/default/s.gif';Ext.QuickTips.init(); // viewport panels varnorthPanel = new Ext.Panel({ id: 'north-panel', height : 50,region: 'north', border: false, title:'Top Panel'});varsouthPanel = new Ext.Panel({ id: 'south-panel', height : 200, region: 'south', title : 'South Panel', collapsible: true, collapsed: true});varwestPanel = new Ext.Panel({ id: 'west-panel', layout: 'fit', width: 250, region: 'west', title: 'Navigation', collapsible: true });varcenterPanel = new Ext.Panel({ region: 'center' ,layout: 'fit', title: 'Content Panel' });// viewportnew Ext.Viewport({id: 'id-viewport' ,layout : 'border' ,items : [northPanel,southPanel,westPanel,centerPanel]});});
  • 28. Here is object oriented programming with JavaScriptWe will create View, ViewLayout.js Class, which will render this Border Layout.We will modify Main.js and will create ViewLayout.js in directory package2Add entry in Index.html for ViewLayout.js, Main.jsOO
  • 29. Index.html<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Basic Setup</title> <!-- Bring in the ExtJs Libraries and CSS --> <link rel="stylesheet" type="text/css" href="lib/ext/resources/css/ext-all.css"/> <script type="text/javascript" src="lib/ext/adapter/ext/ext-base.js"></script> <script type="text/javascript" src="lib/ext/ext-all.js"></script> <!-- Place the page specific js here --><script type="text/javascript" src="lib/com/company/hello/package2/Main.js"></script> <script type="text/javascript" src="lib/com/company/hello/package2/ViewLayout.js"> </script></head>
  • 30. ViewLayout.jsExt.ns("com.company.hello.package2");(function(){varViewLayout = Ext.extend(Object,{ constructor: function(config){Ext.apply(this, config); }, // creating page layout, code goes here /* public */ createLayout: function(){ // viewport panels varnorthPanel = new Ext.Panel({ id: 'north-panel', height : 50,region: 'north', border: false, title:‘ Top Panel'});varsouthPanel = new Ext.Panel({ id: 'south-panel', height : 200, region: 'south', title : 'South Panel', collapsible: true, collapsed: true });varwestPanel = new Ext.Panel({ id: 'west-panel', layout: 'fit', width: 250, region: 'west', title: 'Navigation', collapsible: true });varcenterPanel = new Ext.Panel({ region: 'center' ,layout: 'fit', title: 'Content Panel'});code continues..
  • 31. Continued.. // viewport new Ext.Viewport({ id: 'id-viewport' ,layout : 'border' ,items : [northPanel, southPanel, westPanel, centerPanel] });} }); com.company.hello.package2.ViewLayout = ViewLayout;})();
  • 32. Main.jsExt.onReady(function(){ // Mandatory: need to add this spacer /*[relative path to..]*/Ext.BLANK_IMAGE_URL = 'lib/ext/resources/images/default/s.gif';Ext.QuickTips.init(); // main execution start here, user defined functionvaronModuleLoad = function(){varviewLayout = new com.company.hello.package2.ViewLayout();viewLayout.createLayout(); } // main starting pointonModuleLoad();});
  • 35. SingletonExt.ns("com.netapp.hello.package1"); (function() {varSingletonModel = Ext.extend(Object, { _instance : null ,constructor : function() { console.log("Singleton constructor called : " + this.getInstance()); } ,getInstance : function() { if (this._instance === null) {this._instance = this.createInstance(); } return this._instance; } ,createInstance : function() { return 10; } }); com.netapp.hello.package1.SingletonModel = SingletonModel;})()
  • 38. Use reusable code Object Oriented Approach Modularize codeDo not access DOM frequentlyIts computational heavy codeUse Lazy loading, wherever possibleBut avoid heavy nesting Use of event delegationEvents should be assigned to a smaller subset of the document/element, rather than each individual element, this uses JavaScript’s event bubbling notion.  this approach takes less memory in browserContinued..
  • 39. Use of JavaScript minification, obfuscaterYUI compressor, Linters  (jsonlint.com, jslint.com)Use of efficient programming practices in JavaScript Example: String manipulation - instead of string concatenation using ‘+’ operator, use of array’s .join() function, this way it will be better garbage collected.Cross Browser Scripting: using web standards, feature detection techniques instead browser detection technique and browser specific codeRemove listeners which are not in use anymoreContinued..
  • 40. Loops are heavy, it can be optimized by using simple techniquesIn for loop, whenever reading length of array, store it in some variable instead of reading it again and again using array.lengthAvoid creating lot of HTML code with JavaScriptContinued..
  • 41. I will update these notes periodically with my experiments, stay tuned..Note