2 ______________________________________________
4 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.
6 This 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:
8 - Section I: "Overview" explains the need for a robust class system
9 - Section II: "Naming Conventions" discusses the best practices for naming classes, methods, properties, variables and files.
10 - Section III: "Hands-on" provides detailed step-by-step code examples
11 - Section IV: "Errors Handling & Debugging" gives useful tips & tricks on how to deal with exceptions
16 Ext 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:
18 - familiar and simple to learn
19 - fast to develop, easy to debug, painless to deploy
20 - well-organized, extensible and maintainable
22 JavaScript 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.
24 [Class-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.
26 Each 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.
29 ## II. Naming Conventions
32 Using consistent naming conventions throughout your code base for classes, namespaces and filenames helps keep your code organized, structured and readable.
36 Class 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:
38 - `MyCompany.useful_util.Debug_Toolbar` is discouraged
39 - `MyCompany.util.Base64` is acceptable
41 Class 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:
43 MyCompany.data.CoolProxy
46 The top-level namespaces and the actual class names should be in CamelCased, everything else should be all lower-cased. For example:
48 MyCompany.form.action.AutoLoad
50 Classes that are not distributed by Sencha should never use `Ext` as the top-level namespace.
52 Acronyms should also follow CamelCased convention listed above. For example:
54 - `Ext.data.JsonProxy` instead of `Ext.data.JSONProxy`
55 - `MyCompany.util.HtmlParser` instead of `MyCompary.parser.HTMLParser`
56 - `MyCompany.server.Http` instead of `MyCompany.server.HTTP`
61 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:
63 - `Ext.util.Observable` is stored in `path/to/src/Ext/util/Observable.js`
64 - `Ext.form.action.Submit` is stored in `path/to/src/Ext/form/action/Submit.js`
65 - `MyCompany.chart.axis.Numeric` is stored in `path/to/src/MyCompany/chart/axis/Numeric.js`
67 `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.
69 ### 3) Methods and Variables
71 - 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.
73 - Method and variable names should always be in camelCased. This also applies to acronyms.
76 - Acceptable method names:
78 getHtml() instead of getHTML()
79 getJsonResponse() instead of `getJSONResponse()
80 parseXmlContent() instead of `parseXMLContent()
81 - Acceptable variable names:
89 - Class property names follow the exact same convention with methods and variables mentioned above, except the case when they are static constants.
91 - Static class properties that are constants should be all upper-cased. For example:
92 - `Ext.MessageBox.YES = "Yes"`
93 - `Ext.MessageBox.NO = "No"`
94 - `MyCompany.alien.Math.PI = "4.13"`
102 #### 1.1) The Old Way
103 If you have ever used any previous version of Ext JS, you are certainly familiar with `Ext.extend` to create a class:
105 var MyWindow = Ext.extend(Object, { ... });
107 This 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.
109 Let's take a look at another example:
111 My.cool.Window = Ext.extend(Ext.Window, { ... });
113 In this example we want to [namespace][] our new class, and make it extend from `Ext.Window`. There are two concerns we need to address:
115 1. `My.cool` needs to be an existing object before we can assign `Window` as its property
116 2. `Ext.Window` needs to exist / loaded on the page before it can be referenced
118 The 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.
121 My.cool.Window = Ext.extend(Ext.Window, { ... });
123 The 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.
127 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:
129 Ext.define(className, members, onClassCreated);
131 - `className`: The class name
132 - `members` is an object represents a collection of class members in key-value pairs
133 - `onClassCreated` 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 IV](#)
137 Ext.define('My.sample.Person', {
140 constructor: function(name) {
148 eat: function(foodType) {
149 alert(this.name + " is eating: " + foodType);
155 var aaron = Ext.create('My.sample.Person', 'Aaron');
156 aaron.eat("Salad"); // alert("Aaron is eating: Salad");
158 Note 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](#/guide/getting_started)
162 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:
164 - Configurations are completely encapsulated from other class members
165 - Getter and setter, methods for every config property are automatically generated into the class' prototype during class creation if the class does not have these methods already defined.
166 - An `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.
170 Ext.define('My.own.Window', {
184 constructor: function(config) {
185 this.initConfig(config);
190 applyTitle: function(title) {
191 if (!Ext.isString(title) || title.length === 0) {
192 alert('Error: Title must be a valid non-empty string');
199 applyBottomBar: function(bottomBar) {
200 if (bottomBar && bottomBar.enabled) {
201 if (!this.bottomBar) {
202 return Ext.create('My.own.WindowBottomBar', bottomBar);
205 this.bottomBar.setConfig(bottomBar);
211 And here's an example of how it can be used:
213 var myWindow = Ext.create('My.own.Window', {
214 title: 'Hello World',
220 alert(myWindow.getTitle()); // alerts "Hello World"
222 myWindow.setTitle('Something New');
224 alert(myWindow.getTitle()); // alerts "Something New"
226 myWindow.setTitle(null); // alerts "Error: Title must be a valid non-empty string"
228 myWindow.setBottomBar({ height: 100 }); // Bottom bar's height is changed to 100
233 Static members can be defined using the `statics` config
235 Ext.define('Computer', {
238 factory: function(brand) {
239 // 'this' in static methods refer to the class itself
240 return new this({brand: brand});
248 constructor: function(config) {
249 this.initConfig(config);
251 // the 'self' property of an instance refers to its class
252 this.self.instanceCount ++;
258 var dellComputer = Computer.factory('Dell');
259 var appleComputer = Computer.factory('Mac');
261 alert(appleComputer.getBrand()); // using the auto-generated getter to get the value of a config property. Alerts "Mac"
263 alert(Computer.instanceCount); // Alerts "2"
266 ## IV. Errors Handling & Debugging
269 Ext JS 4 includes some useful features that will help you with debugging and error handling.
271 - You 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:
273 throw new Error('['+ Ext.getDisplayName(arguments.callee) +'] Some message here');
275 - 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:
277 {@img call-stack.png Call Stack}
279 [prototype-oriented]: http://en.wikipedia.org/wiki/Prototype-based_programming
280 [class-based]: http://en.wikipedia.org/wiki/Class-based_programming
281 [Class-based languages]: http://en.wikipedia.org/wiki/Category:Class-based_programming_languages
282 [namespace]: http://en.wikipedia.org/wiki/Namespace_(computer_science)
283 [examples-download]: #download
287 - [Dynamic Loading and the New Class System](http://www.sencha.com/blog/countdown-to-ext-js-4-dynamic-loading-and-new-class-system)
288 - [Classes in Ext JS 4: Under the Hood](http://edspencer.net/2011/01/classes-in-ext-js-4-under-the-hood.html)
289 - [The Class Definition Pipeline](http://edspencer.net/2011/01/ext-js-4-the-class-definition-pipeline.html)