X-Git-Url: http://git.ithinksw.org/extjs.git/blobdiff_plain/6746dc89c47ed01b165cc1152533605f97eb8e8d..HEAD:/docs/guides/class_system/README.js?ds=sidebyside diff --git a/docs/guides/class_system/README.js b/docs/guides/class_system/README.js index 3d6c6064..f0f93d81 100644 --- a/docs/guides/class_system/README.js +++ b/docs/guides/class_system/README.js @@ -1,3 +1 @@ -Ext.data.JsonP.class_system({ - "guide": "
For the first time in its history, Ext JS went through a huge refactoring from the ground up with the new class system. The new architecture stands behind almost every single class written in Ext JS 4.x, hence it's important to understand it well before you start coding.
\n\nThis manual is intended for any developer who wants to create new or extend existing classes in Ext JS 4.x. It's divided into 3 main sections:
\n\nExt JS 4 ships with more than 300 classes. We have a huge community of more than 200,000 developers to date, coming from various programming backgrounds all over the world. At that scale of a framework, we face a big challange of providing a common code architecture that is:
\n\nJavaScript is a classless, prototype-oriented language. Hence by nature, one of the language's most powerful features is flexibility. It can get the same job done by many different ways, in many different coding styles and techniques. That feature, however, comes with the cost of unpredictability. Without a unified structure, JavaScript code can be really hard to understand, maintain and re-use.
\n\nClass-based programming, on the other hand, still stays as the most popular model of OOP. Class-based languages usually require strong-typing, provide encapsulation, and come with standard coding convention. By generally making developers adhere to a large set of principle, written code is more likely to be predictable, extensible and scalable over time. However, they don't have the same dynamic capability found in such language as JavaScript.
\n\nEach approach has its own pros and cons, but can we have the good parts of both at the same time while concealing the bad parts? The answer is yes, and we've implemented the solution in Ext JS 4.
\n\nClass names may only contain alphanumeric characters. Numbers are permitted but are discouraged in most cases, unless they belong to a technical term. Do not use underscores, hyphens, or any other nonalphanumeric character. For example:
\n\nMyCompany.useful_util.Debug_Toolbar
is discouragedMyCompany.util.Base64
is acceptableClass names should be grouped into packages where appropriate and properly namespaced using object property dot-notation (.). At the minimum, there should be one unique top-level namespace followed by the class name. For example:
\n\nMyCompany.data.CoolProxy
MyCompany.Application
The top-level namespaces and the actual class names should be in CamelCased, everything else should be all lower-cased. For example:
\n\nMyCompany.form.action.AutoLoad
Classes that are not distributed by Sencha should never use Ext
as the top-level namespace.
Acronyms should also follow CamelCased convention listed above. For example:
\n\nExt.data.JsonProxy
instead of Ext.data.JSONProxy
MyCompany.util.HtmlParser
instead of MyCompary.parser.HTMLParser
MyCompany.server.Http
instead of MyCompany.server.HTTP
Ext.util.Observable
is stored in path/to/src/Ext/util/Observable.js
Ext.form.action.Submit
is stored in path/to/src/Ext/form/action/Submit.js
MyCompany.chart.axis.Numeric
is stored in path/to/src/MyCompany/chart/axis/Numeric.js
whereby path/to/src
is the directory of your application's classes. All classes should stay inside one directory and should be properly namespaced for the best development, maintenance and deployment experience.
Similarly to class names, method and variable names may only contain alphanumeric characters. Numbers are permitted but are discouraged in most cases, unless they belong to a technical term. Do not use underscores, hyphens, or any other nonalphanumeric character.
Method and variable names should always be in camelCased. This also applies to acronyms.
Examples
\n\nencodeUsingMd5()
getHtml()
instead of getHTML()
getJsonResponse()
instead of getJSONResponse()
parseXmlContent()
instead of parseXMLContent()
var isGoodName
var base64Encoder
var xmlReader
var httpServer
Class property names follow the exact same convention with methods and variables mentioned above, except the case when they are static constants.
Static class properties that are constants should be all upper-cased. For example:
\n\nExt.MessageBox.YES = \"Yes\"
Ext.MessageBox.NO = \"No\"
MyCompany.alien.Math.PI = \"4.13\"
If you have ever used any previous version of Ext JS, you are certainly familiar with Ext.extend
to create a class:
var MyWindow = Ext.extend(Object, { ... });\n
\n\nThis approach is easy to followed to create a new class that inherit from another. Other than direct inheritance, however, we didn't have a fluent API for other aspects of class creation, such as configuration, statics and mixins. We will be reviewing these items in details shortly.
\n\nLet's take a look at another example:
\n\nMy.cool.Window = Ext.extend(Ext.Window, { ... });\n
\n\nIn this example we want to namespace our new class, and make it extend from Ext.Window
. There are two concerns we need to address:
My.cool
needs to be an existing object before we can assign Window
as its propertyExt.Window
needs to exist / loaded on the page before it can be referencedThe first item is usually solved with Ext.namespace
(aliased by Ext.ns
). This method recursively transverse through the object / property tree and create them if they don't exist yet. The boring part is you need to remember adding them above Ext.extend
all the time.
Ext.ns('My.cool');\nMy.cool.Window = Ext.extend(Ext.Window, { ... });\n
\n\nThe second issue, however, is not easy to address because Ext.Window
might depend on many other classes that it directly / indirectly inherits from, and in turn, these dependencies might depend on other classes to exist. For that reason, applications written before Ext JS 4 usually include the whole library in the form of ext-all.js
even though they might only need a small portion of the framework.
Ext JS 4 eliminates all those drawbacks with just one single method you need to remember for class creation: Ext.define
. Basic syntax:
Ext.define({String} className, {Object} members, {Function} onClassCreated);\n
\n\nclassName
: The class namemembers
is an object represents a collection of class members in key-value pairsonClassCreated
is an optional function callback to be invoked when all dependencies of this class are ready, and the class itself is fully created. Due to the new asynchronous nature of class creation, this callback can be useful in many situations. These will be discussed further in Section IVExample:
\n\nExt.define('My.sample.Person', {\n name: 'Unknown',\n\n constructor: function(name) {\n if (name) {\n this.name = name;\n }\n\n return this;\n },\n\n eat: function(foodType) {\n alert(this.name + \" is eating: \" + foodType);\n\n return this;\n }\n});\n\nvar aaron = Ext.create('My.sample.Person');\n aaron.eat(\"Salad\"); // alert(\"Aaron is eating: Salad\");\n
\n\nNote we created a new instance of My.sample.Person
using the Ext.create()
method. We could have used the new
keyword (new My.sample.Person()
). However it is recommended to get in the habit of always using Ext.create
since it allows you to take advantage of dynamic loading. For more info on dynamic loading see the Getting Started guide
Previous to version 4, we didn't really have a way to distinguish between class properties and user-supplied configurations. Configurations were defined as normal class properties and documented using @cfg
annotation. Let's take a look at a sample class. It's rather lengthy but it well describes the problems as a whole:
Ext.ns('My.own');\nMy.own.Window = Ext.extend(Object, {\n /** @readonly */\n isWindow: true,\n\n /** @cfg {String} title The default window's title */\n title: 'Title Here',\n\n /** @cfg {Object} bottomBar The default config for the bottom bar */\n bottomBar: {\n enabled: true,\n height: 50,\n resizable: false\n },\n\n constructor: function(config) {\n Ext.apply(this, config || {});\n\n this.setTitle(this.title);\n this.setBottomBar(this.bottomBar);\n\n return this;\n },\n\n setTitle: function(title) {\n // Change title only if it's a non-empty string\n if (!Ext.isString(title) || title.length === 0) {\n alert('Error: Title must be a valid non-empty string');\n }\n else {\n this.title = title;\n }\n\n return this;\n },\n\n getTitle: function() {\n return this.title;\n },\n\n setBottomBar: function(bottomBar) {\n // Create a new instance of My.own.WindowBottomBar if it doesn't exist\n // Change the config of the existing instance otherwise\n if (bottomBar && bottomBar.enabled) {\n if (!this.bottomBar) {\n this.bottomBar = Ext.create('My.own.WindowBottomBar', bottomBar);\n }\n else {\n this.bottomBar.setConfig(bottomBar);\n }\n }\n\n return this;\n },\n\n getBottomBar: function() {\n return this.bottomBar;\n }\n});\n
\n\nIn short, My.own.Window
:
title
and bottomBar
to be changed during run-time via settersThis approach has one advantage, yet it's the one drawback at the same time: you can overwrite any members of this class' instances during instantiation, including private methods and properties that should never be overwritten. The trade-off of encapsutation for flexibilty caused misusage in many applications in the past, which led to poor design as well as bad debugging and maintenance experience.
\n\nFurther more, there are other limitations:
\n\nExt.apply
doesn't merge object properties recursively. So in this example, you can't just override bottomBar.height
to 60
, for instance, without supplying other default properties of bottomBar
as well.
Getters and setters have to be manually defined for each and every config property. It's not programmatically possible to clearly tell what properties are configurations, hence setters and getters can't be automatically generated.
In Ext JS 4, we introduce a dedicated config
property that gets processed by the powerful Ext.Class pre-processors before the class is created. Let's rewrite the above example:
Ext.define('My.own.Window', {\n /** @readonly */\n isWindow: true,\n\n config: {\n title: 'Title Here',\n\n bottomBar: {\n enabled: true,\n height: 50,\n resizable: false\n }\n },\n\n constructor: function(config) {\n this.initConfig(config);\n\n return this;\n },\n\n applyTitle: function(title) {\n if (!Ext.isString(title) || title.length === 0) {\n alert('Error: Title must be a valid non-empty string');\n }\n else {\n return title;\n }\n },\n\n applyBottomBar: function(bottomBar) {\n if (bottomBar && bottomBar.enabled) {\n if (!this.bottomBar) {\n return Ext.create('My.own.WindowBottomBar', bottomBar);\n }\n else {\n this.bottomBar.setConfig(bottomBar);\n }\n }\n }\n});\n
\n\nAnd here's an example of how it can be used:
\n\nvar myWindow = Ext.create('My.own.Window', {\n title: 'Hello World',\n bottomBar: {\n height: 60\n }\n});\n\nalert(myWindow.getTitle()); // alerts \"Hello World\"\n\nmyWindow.setTitle('Something New');\n\nalert(myWindow.getTitle()); // alerts \"Something New\"\n\nmyWindow.setTitle(null); // alerts \"Error: Title must be a valid non-empty string\"\n\nmyWindow.setBottomBar({ height: 100 }); // Bottom bar's height is changed to 100\n
\n\nWith these changes:
\n\nMy.own.Window
class' code is significantly reduced, with even more functionalitiesapply
method is also generated for every config property. The auto-generated setter method calls the apply
method internally before setting the value. Override the apply
method for a config property if you need to run custom logic before setting the value. If apply
does not return a value then the setter will not set the value. For example see applyTitle
above.Static members can be defined using the statics
config
Ext.define('Computer', {\n statics: {\n instanceCount: 0,\n factory: function(brand) {\n // 'this' in static methods refer to the class itself\n return new this({brand: brand});\n }\n },\n\n config: {\n brand: null\n },\n\n constructor: function(config) {\n this.initConfig(config);\n\n // the 'self' property of an instance refers to its class\n this.self.instanceCount ++;\n\n return this;\n }\n});\n\nvar dellComputer = Computer.factory('Dell');\nvar appleComputer = Computer.factory('Mac');\n\nalert(appleComputer.getBrand()); // using the auto-generated getter to get the value of a config property. Alerts \"Mac\"\n\nalert(Computer.instanceCount); // Alerts \"2\"\n
\n\nExt JS 4 supports inheritance through both subclassing and mixins. For more information on inheritance see the documentation for Ext.Class
\n\nAnother new feature introduced in Ext JS 4 is dynamic loading of dependencies. For more information see the documentation for Ext.Loader
\n\nExt JS 4 includes some useful features that will help you with debugging and error handling.
\n\nYou can use Ext.getDisplayName()
to get the display name of any method. This is especially useful for throwing errors that have the class name and method name in their description:
throw new Error('['+ Ext.getDisplayName(arguments.callee) +'] Some message here');\n
When an error is thrown in any method of any class defined using Ext.define()
, you should see the method and class names in the call stack if you are using a WebKit based browser (Chrome or Safari). For example, here is what it would look like in Chrome:
For the first time in its history, Ext JS went through a huge refactoring from the ground up with the new class system. The new architecture stands behind almost every single class written in Ext JS 4.x, hence it's important to understand it well before you start coding.
\n\nThis manual is intended for any developer who wants to create new or extend existing classes in Ext JS 4.x. It's divided into 4 sections:
\n\nExt JS 4 ships with more than 300 classes. We have a huge community of more than 200,000 developers to date, coming from various programming backgrounds all over the world. At that scale of a framework, we face a big challange of providing a common code architecture that is:
\n\nJavaScript is a classless, prototype-oriented language. Hence by nature, one of the language's most powerful features is flexibility. It can get the same job done by many different ways, in many different coding styles and techniques. That feature, however, comes with the cost of unpredictability. Without a unified structure, JavaScript code can be really hard to understand, maintain and re-use.
\n\nClass-based programming, on the other hand, still stays as the most popular model of OOP. Class-based languages usually require strong-typing, provide encapsulation, and come with standard coding convention. By generally making developers adhere to a large set of principles, written code is more likely to be predictable, extensible and scalable over time. However, they don't have the same dynamic capability found in such language as JavaScript.
\n\nEach approach has its own pros and cons, but can we have the good parts of both at the same time while concealing the bad parts? The answer is yes, and we've implemented the solution in Ext JS 4.
\n\nUsing consistent naming conventions throughout your code base for classes, namespaces and filenames helps keep your code organized, structured and readable.
\n\nClass names may only contain alphanumeric characters. Numbers are permitted but are discouraged in most cases, unless they belong to a technical term. Do not use underscores, hyphens, or any other nonalphanumeric character. For example:
\n\nMyCompany.useful_util.Debug_Toolbar
is discouragedMyCompany.util.Base64
is acceptableClass names should be grouped into packages where appropriate and properly namespaced using object property dot-notation (.). At the minimum, there should be one unique top-level namespace followed by the class name. For example:
\n\nMyCompany.data.CoolProxy\nMyCompany.Application\n
\n\nThe top-level namespaces and the actual class names should be in CamelCased, everything else should be all lower-cased. For example:
\n\nMyCompany.form.action.AutoLoad\n
\n\nClasses that are not distributed by Sencha should never use Ext
as the top-level namespace.
Acronyms should also follow CamelCased convention listed above. For example:
\n\nExt.data.JsonProxy
instead of Ext.data.JSONProxy
MyCompany.util.HtmlParser
instead of MyCompary.parser.HTMLParser
MyCompany.server.Http
instead of MyCompany.server.HTTP
The names of the classes map directly to the file paths in which they are stored. As a result, there must only be one class per file. For example:
\n\nExt.util.Observable
is stored in path/to/src/Ext/util/Observable.js
Ext.form.action.Submit
is stored in path/to/src/Ext/form/action/Submit.js
MyCompany.chart.axis.Numeric
is stored in path/to/src/MyCompany/chart/axis/Numeric.js
path/to/src
is the directory of your application's classes. All classes should stay under this common root and should be properly namespaced for the best development, maintenance and deployment experience.
Similarly to class names, method and variable names may only contain alphanumeric characters. Numbers are permitted but are discouraged in most cases, unless they belong to a technical term. Do not use underscores, hyphens, or any other nonalphanumeric character.
Method and variable names should always be in camelCased. This also applies to acronyms.
Examples
\n\ngetJSONResponse()\n parseXmlContent() instead of
parseXMLContent()Class property names follow the exact same convention with methods and variables mentioned above, except the case when they are static constants.
Static class properties that are constants should be all upper-cased. For example:
\n\nExt.MessageBox.YES = \"Yes\"
Ext.MessageBox.NO = \"No\"
MyCompany.alien.Math.PI = \"4.13\"
If you have ever used any previous version of Ext JS, you are certainly familiar with Ext.extend
to create a class:
var MyWindow = Ext.extend(Object, { ... });\n
\n\nThis approach is easy to follow to create a new class that inherits from another. Other than direct inheritance, however, we didn't have a fluent API for other aspects of class creation, such as configuration, statics and mixins. We will be reviewing these items in details shortly.
\n\nLet's take a look at another example:
\n\nMy.cool.Window = Ext.extend(Ext.Window, { ... });\n
\n\nIn this example we want to namespace our new class, and make it extend from Ext.Window
. There are two concerns we need to address:
My.cool
needs to be an existing object before we can assign Window
as its propertyExt.Window
needs to exist / loaded on the page before it can be referencedThe first item is usually solved with Ext.namespace
(aliased by Ext.ns
). This method recursively transverse through the object / property tree and create them if they don't exist yet. The boring part is you need to remember adding them above Ext.extend
all the time.
Ext.ns('My.cool');\nMy.cool.Window = Ext.extend(Ext.Window, { ... });\n
\n\nThe second issue, however, is not easy to address because Ext.Window
might depend on many other classes that it directly / indirectly inherits from, and in turn, these dependencies might depend on other classes to exist. For that reason, applications written before Ext JS 4 usually include the whole library in the form of ext-all.js
even though they might only need a small portion of the framework.
Ext JS 4 eliminates all those drawbacks with just one single method you need to remember for class creation: Ext.define
. Its basic syntax is as follows:
Ext.define(className, members, onClassCreated);\n
\n\nclassName
: The class namemembers
is an object represents a collection of class members in key-value pairsonClassCreated
is an optional function callback to be invoked when all dependencies of this class are ready, and the class itself is fully created. Due to the new asynchronous nature of class creation, this callback can be useful in many situations. These will be discussed further in Section IVExample:
\n\nExt.define('My.sample.Person', {\n name: 'Unknown',\n\n constructor: function(name) {\n if (name) {\n this.name = name;\n }\n\n return this;\n },\n\n eat: function(foodType) {\n alert(this.name + \" is eating: \" + foodType);\n\n return this;\n }\n});\n\nvar aaron = Ext.create('My.sample.Person', 'Aaron');\n aaron.eat(\"Salad\"); // alert(\"Aaron is eating: Salad\");\n
\n\nNote we created a new instance of My.sample.Person
using the Ext.create()
method. We could have used the new
keyword (new My.sample.Person()
). However it is recommended to get in the habit of always using Ext.create
since it allows you to take advantage of dynamic loading. For more info on dynamic loading see the Getting Started guide
In Ext JS 4, we introduce a dedicated config
property that gets processed by the powerful Ext.Class pre-processors before the class is created. Features include:
apply
method is also generated for every config property. The auto-generated setter method calls the apply
method internally before setting the value. Override the apply
method for a config property if you need to run custom logic before setting the value. If apply
does not return a value then the setter will not set the value. For an example see applyTitle
below.Here's an example:
\n\nExt.define('My.own.Window', {\n /** @readonly */\n isWindow: true,\n\n config: {\n title: 'Title Here',\n\n bottomBar: {\n enabled: true,\n height: 50,\n resizable: false\n }\n },\n\n constructor: function(config) {\n this.initConfig(config);\n\n return this;\n },\n\n applyTitle: function(title) {\n if (!Ext.isString(title) || title.length === 0) {\n alert('Error: Title must be a valid non-empty string');\n }\n else {\n return title;\n }\n },\n\n applyBottomBar: function(bottomBar) {\n if (bottomBar && bottomBar.enabled) {\n if (!this.bottomBar) {\n return Ext.create('My.own.WindowBottomBar', bottomBar);\n }\n else {\n this.bottomBar.setConfig(bottomBar);\n }\n }\n }\n});\n
\n\nAnd here's an example of how it can be used:
\n\nvar myWindow = Ext.create('My.own.Window', {\n title: 'Hello World',\n bottomBar: {\n height: 60\n }\n});\n\nalert(myWindow.getTitle()); // alerts \"Hello World\"\n\nmyWindow.setTitle('Something New');\n\nalert(myWindow.getTitle()); // alerts \"Something New\"\n\nmyWindow.setTitle(null); // alerts \"Error: Title must be a valid non-empty string\"\n\nmyWindow.setBottomBar({ height: 100 }); // Bottom bar's height is changed to 100\n
\n\nStatic members can be defined using the statics
config
Ext.define('Computer', {\n statics: {\n instanceCount: 0,\n factory: function(brand) {\n // 'this' in static methods refer to the class itself\n return new this({brand: brand});\n }\n },\n\n config: {\n brand: null\n },\n\n constructor: function(config) {\n this.initConfig(config);\n\n // the 'self' property of an instance refers to its class\n this.self.instanceCount ++;\n\n return this;\n }\n});\n\nvar dellComputer = Computer.factory('Dell');\nvar appleComputer = Computer.factory('Mac');\n\nalert(appleComputer.getBrand()); // using the auto-generated getter to get the value of a config property. Alerts \"Mac\"\n\nalert(Computer.instanceCount); // Alerts \"2\"\n
\n\nExt JS 4 includes some useful features that will help you with debugging and error handling.
\n\nYou can use Ext.getDisplayName()
to get the display name of any method. This is especially useful for throwing errors that have the class name and method name in their description:
throw new Error('['+ Ext.getDisplayName(arguments.callee) +'] Some message here');\n
When an error is thrown in any method of any class defined using Ext.define()
, you should see the method and class names in the call stack if you are using a WebKit based browser (Chrome or Safari). For example, here is what it would look like in Chrome: