Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / docs / guide / class_system.html
1 <!DOCTYPE html><html><head><title>Sencha Documentation Project</title><script type="text/javascript" src="../ext-all.js"></script><link rel="stylesheet" href="../reset.css" type="text/css"><link rel="stylesheet" href="../scrollbars.css" type="text/css"><link rel="stylesheet" href="../docs.css" type="text/css"><link id="styleCss" rel="stylesheet" href="../style.css" type="text/css"><script type="text/javascript" src="../prettify.js"></script><link rel="stylesheet" href="../prettify.css" type="text/css"><!-- link(rel: 'stylesheet', href: req.baseURL + '/css/ext4.css', type: 'text/css')--><link rel="shortcut icon" type="image/ico" href="../favicon.ico"><!--[if IE]>
2 <style type="text/css">.head-band { display: none; }
3 .header { border: 0; top: 0; left: 0px; background: url(../header.gif) repeat-x; }
4 .doc-tab .members .member a.more { background-color: #efefef; }
5 </style><link rel="stylesheet" href="/new/css/ie.css" type="text/css"><![endif]-->
6 </head><body id="ext-body" class="iScroll"><div id="notice" class="notice">For up to date documentation and features, visit 
7 <a href="http://docs.sencha.com/ext-js/4-0">http://docs.sencha.com/ext-js/4-0</a></div><div class="wrapper"><div class="head-band"></div><div class="header"><h2><a href="../index.html">Sencha Documentation</a></h2></div><div id="search"><form><input type="text" placeholder="Search" id="search-field" autocomplete="off" name="q"></form><div id="search-box"></div></div><div id="treePanel"></div><div id="container"><script type="text/javascript">
8
9     req = {
10         liveURL: '.',
11         standAloneMode: true,
12         origDocClass: 'undefined',
13         docClass: 'undefined',
14         docReq: 'undefined',
15         version: '4.0',
16         baseURL: '.',
17         baseDocURL: '.',
18         baseProdURL: '.'
19     };
20
21     clsInfo = {};
22
23
24
25 </script>
26
27 <script type="text/javascript" src="../search.js"></script>
28 <!--script type="text/javascript" src="/new/javascripts/app/examples.js"></script-->
29 <script type="text/javascript" src="../class_tree.js"></script>
30 <script type="text/javascript" src="../class_doc.js"></script>
31 <div id="top-block" class="top-block"></div><div id="docContent"><div class="guide"><h1>Ext JS 4 Class System</h1>
32
33 <hr></hr>
34
35 <p>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.</p>
36
37 <p>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 3 main sections:</p>
38
39 <ul><li>Section I: <a href="class_system.html#">"Overview"</a> explains the need for a robust class system</li><li>Section II: <a href="class_system.html#">"Hands-on"</a> provides detailed step-by-step code examples</li><li>Section III: <a href="class_system.html#">"Errors Handling & Debugging"</a> gives useful tips & tricks on how to deal with exceptions</li><li>Section III: <a href="class_system.html#">"Under the Hood"</a> discusses about technical concept and implementation</li></ul>
40
41 <p>All code examples used in this manual can be downloaded <a href="class_system.html#download">here</a></p>
42
43 <h2>I. Overview</h2>
44
45 <hr></hr>
46
47 <p>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:</p>
48
49 <ul><li>familiar and simple to learn</li><li>fast to develop, easy to debug, painless to deploy</li><li>well-organized, extensible and maintainable</li></ul>
50
51 <p>JavaScript is a classless, <a href="http://en.wikipedia.org/wiki/Prototype-based_programming">prototype-oriented</a> 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.</p>
52
53 <p><a href="http://en.wikipedia.org/wiki/Class-based_programming">Class-based</a> programming, on the other hand, still stays as the most popular model of OOP. <a href="http://en.wikipedia.org/wiki/Category:Class-based_programming_languages">Class-based languages</a> 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.</p>
54
55 <p>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.</p>
56
57 <h2>II. Naming Convention</h2>
58
59 <h3>1) Classes</h3>
60
61 <ul><li><p>Class names may only contain <strong>alphanumeric</strong> 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:</p><ul><li><code>MyCompany.useful_util.Debug_Toolbar</code> is discouraged</li><li><p><code>MyCompany.util.Base64</code> is acceptable</p></li></ul></li><li><p>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:</p><ul><li><code>MyCompany.data.CoolProxy</code></li><li><p><code>MyCompany.Application</code></p></li></ul></li><li><p>The top-level namespaces and the actual class names should be in CamelCased, everything else should be all lower-cased. For example:</p><ul><li><p><code>MyCompany.form.action.AutoLoad</code></p></li></ul></li><li><p>Classes that are not distributed by Sencha should never use <code>Ext</code> as the top-level namespace.</p></li><li><p>Acronyms should also follow CamelCased convention listed above. For example:</p><ul><li><code>Ext.data.JsonProxy</code> instead of <code>Ext.data.JSONProxy</code></li><li><code>MyCompany.util.HtmlParser</code> instead of <code>MyCompary.parser.HTMLParser</code></li><li><code>MyCompany.server.Http</code> instead of <code>MyCompany.server.HTTP</code></li></ul></li></ul>
62
63 <h3>2) Source Files</h3>
64
65 <ul><li><p>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:</p><ul><li><code>Ext.util.Observable</code> is stored in <code>path/to/src/Ext/util/Observable.js</code></li><li><code>Ext.form.action.Submit</code> is stored in <code>path/to/src/Ext/form/action/Submit.js</code></li><li><p><code>MyCompany.chart.axis.Numeric</code> is stored in <code>path/to/src/MyCompany/chart/axis/Numeric.js</code></p><p>whereby <code>path/to/src</code> 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.</p></li></ul></li></ul>
66
67 <h3>3) Methods and Variables</h3>
68
69 <ul><li><p>Similarly to class names, method and variable names may only contain <strong>alphanumeric</strong> 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.</p></li><li><p>Method and variable names should always be in camelCased. This also applies to acronyms.</p></li><li><p>Examples</p><ul><li>Acceptable method names:<ul><li><code>encodeUsingMd5()</code></li><li><code>getHtml()</code> instead of <code>getHTML()</code></li><li><code>getJsonResponse()</code> instead of <code>getJSONResponse()</code></li><li><code>parseXmlContent()</code> instead of <code>parseXMLContent()</code></li></ul></li><li>Acceptable variable names:<ul><li><code>var isGoodName</code></li><li><code>var base64Encoder</code></li><li><code>var xmlReader</code></li><li><code>var httpServer</code></li></ul></li></ul></li></ul>
70
71 <h3>4) Properties</h3>
72
73 <ul><li><p>Class property names follow the exact same convention with methods and variables mentioned above, except the case when they are static constants.</p></li><li><p>Static class properties that are constants should be all upper-cased. For example:</p><ul><li><code>Ext.MessageBox.YES = "Yes"</code></li><li><code>Ext.MessageBox.NO  = "No"</code></li><li><code>MyCompany.alien.Math.PI = "4.13"</code></li></ul></li></ul>
74
75 <h2>II. Hands-on</h2>
76
77 <hr></hr>
78
79 <h3>1. Declaration</h3>
80
81 <h4>1.1) The Old Way</h4>
82
83 <p>If you have ever used any previous version of Ext JS, you are certainly familiar with <code>Ext.extend</code> to create a class:</p>
84
85 <pre class="prettyprint"><code>var MyWindow = Ext.extend(Object, { ... });</code></pre>
86
87 <p>This 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.</p>
88
89 <p>Let's take a look at another example:</p>
90
91 <pre class="prettyprint"><code>My.cool.Window = Ext.extend(Ext.Window, { ... });</code></pre>
92
93 <p>In this example we want to <a href="http://en.wikipedia.org/wiki/Namespace_(computer_science)">namespace</a> our new class, and make it extend from <code>Ext.Window</code>. There are two concerns we need to address:</p>
94
95 <ol><li><code>My.cool</code> needs to be an existing object before we can assign <code>Window</code> as its property</li><li><code>Ext.Window</code> needs to exist / loaded on the page before it can be referenced</li></ol>
96
97 <p>The first item is usually solved with <code>Ext.namespace</code> (aliased by <code>Ext.ns</code>). 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 <code>Ext.extend</code> all the time.</p>
98
99 <pre class="prettyprint"><code>Ext.ns('My.cool');
100 My.cool.Window = Ext.extend(Ext.Window, { ... });</code></pre>
101
102 <p>The second issue, however, is not easy to address because <code>Ext.Window</code> 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 <code>ext-all.js</code> even though they might only need a small portion of the framework.</p>
103
104 <h3>1.2) The New Way</h3>
105
106 <p>Ext JS 4 eliminates all those drawbacks with just one single method you need to remember for class creation: <code>Ext.define</code>. Basic syntax:</p>
107
108 <pre class="prettyprint"><code>Ext.define({String} className, {Object} members, {Function} onClassCreated);</code></pre>
109
110 <ul><li><code>className</code>: The <a href="class_system.html#">class name</a></li><li><code>members</code> is an object represents a collection of class members in key-value pairs</li><li><code>onClassCreated</code> 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 <a href="class_system.html#">new asynchronous nature</a> of class creation, this callback can be useful in many situations. These will be discussed further in <a href="class_system.html#">Section IV</a></li></ul>
111
112 <p><strong>Example:</strong></p>
113
114 <pre class="prettyprint"><code>Ext.define('My.sample.Person', {
115     name: 'Unknown',
116
117     constructor: function(name) {
118         if (name) {
119             this.name = name;
120         }
121
122         return this;
123     },
124
125     eat: function(foodType) {
126         alert(this.name + " is eating: " + foodType);
127
128         return this;
129     }
130 });
131
132 var aaron = new My.sample.Person("Aaron");
133     aaron.eat("Salad"); // alert("Aaron is eating: Salad");</code></pre>
134
135 <h3>2. Configuration</h3>
136
137 <h4>2.1) The Old Way</h4>
138
139 <p>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 <code>@cfg</code> annotation. Let's take a look at a sample class. It's rather lengthy but it well describes the problems as a whole:</p>
140
141 <pre class="prettyprint"><code>Ext.ns('My.sample');
142 My.own.Window = Ext.extend(Object, {
143    /** @readonly */
144     isWindow: true,
145
146    /** @cfg {String} title The default window's title */
147     title: 'Title Here',
148
149    /** @cfg {Object} bottomBar The default config for the bottom bar */
150     bottomBar: {
151         enabled: true,
152         height: 50,
153         resizable: false
154     },
155
156     constructor: function(config) {
157         Ext.apply(this, config || {});
158
159         this.setTitle(this.title);
160         this.setBottomBar(this.bottomBar);
161
162         return this;
163     },
164
165     setTitle: function(title) {
166         // Change title only if it's a non-empty string
167         if (!Ext.isString(title) || title.length === 0) {
168             alert('Error: Title must be a valid non-empty string');
169         }
170         else {
171             this.title = title;
172         }
173
174         return this;
175     },
176
177     getTitle: function() {
178         return this.title;
179     },
180
181     setBottomBar: function(bottomBar) {
182         // Create a new instance of My.own.WindowBottomBar if it doesn't exist
183         // Change the config of the existing instance otherwise
184         if (bottomBar && bottomBar.enabled) {
185             if (!this.bottomBar) {
186                 this.bottomBar = new My.own.WindowBottomBar(bottomBar);
187             }
188             else {
189                 this.bottomBar.setConfig(bottomBar);
190             }
191         }
192
193         return this;
194     },
195
196     getBottomBar: function() {
197         return this.bottomBar;
198     }
199 });</code></pre>
200
201 <p>In short, <code>My.own.Window</code>:</p>
202
203 <ul><li>accepts a config object during instantiation, then merge with the default properties of the class</li><li>allows <code>title</code> and <code>bottomBar</code> to be changed during run-time via setters</li></ul>
204
205 <p>This 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.</p>
206
207 <p>Further more, there are other limitations:</p>
208
209 <ul><li><p><code>Ext.apply</code> doesn't merge object properties recursively. So in this example, you can't just override <code>bottomBar.height</code> to <code>60</code>, for instance, without supplying other default properties of <code>bottomBar</code> as well.</p></li><li><p>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.</p></li></ul>
210
211 <h4>2.2) The New Way</h4>
212
213 <p>In Ext JS 4, we introduce a dedicated <code>config</code> property that gets processed by the powerful <a href="class_system.html#">Ext.Class pre-processors</a> before the class is created. Let's rewrite the above example:</p>
214
215 <pre class="prettyprint"><code>Ext.define('My.own.Window', {
216    /** @readonly */
217     isWindow: true,
218
219     config: {
220         title: 'Title Here',
221
222         bottomBar: {
223             enabled: true,
224             height: 50,
225             resizable: false
226         }
227     },
228
229     constructor: function(config) {
230         this.initConfig(config);
231
232         return this;
233     },
234
235     applyTitle: function(title) {
236         if (!Ext.isString(title) || title.length === 0) {
237             alert('Error: Title must be a valid non-empty string');
238         }
239         else {
240             return title;
241         }
242     },
243
244     applyBottomBar: function(bottomBar) {
245         if (bottomBar && bottomBar.enabled) {
246             if (!this.bottomBar) {
247                 return new My.own.WindowBottomBar(bottomBar);
248             }
249             else {
250                 this.bottomBar.setConfig(bottomBar);
251             }
252         }
253     }
254 });</code></pre>
255
256 <p>And here's an example of how it can be used:</p>
257
258 <pre class="prettyprint"><code>var myWindow = new My.own.Window({
259     title: 'Hello World',
260     bottomBar: {
261         height: 60
262     }
263 });
264
265 alert(myWindow.getTitle()); // alerts "Hello World"
266
267 myWindow.setTitle('Something New');
268
269 alert(myWindow.getTitle()); // alerts "Something New"
270
271 myWindow.setTitle(null); // alerts "Error: Title must be a valid non-empty string"
272
273 myWindow.setBottomBar({ height: 100 }); // Bottom bar's height is changed to 100</code></pre>
274
275 <p>With these changes:</p>
276
277 <ul><li><code>My.own.Window</code> class' code is significantly reduced, with even more functionalities</li><li>Configurations are completely encapsulated from other class members</li><li>Setters and getters, together with <a href="class_system.html#">`apply*`</a> and <a href="class_system.html#">`reset*`</a> 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.</li></ul>
278
279 <h4>2.3) `apply*`</h4>
280
281 <h3>3. Statics</h3>
282
283 <h3>4. Inheritance</h3>
284
285 <h3>5. Mixins</h3>
286
287 <h3>6. Dependencies</h3>
288
289 <h2>III. Errors Handling & Debugging</h2>
290
291 <hr></hr>
292
293 <h2>IV. Under the Hood</h2>
294
295 <hr></hr>
296
297 <h3>1. Ext.Base</h3>
298
299 <h3>2. Ext.Class and Pre-processors</h3>
300
301 <h3>3. Ext.ClassManager and Post-processors</h3>
302
303 <h3>4. Ext.Loader</h3>
304
305 <h2>See Also</h2>
306
307 <ul><li><a href="http://www.sencha.com/blog/countdown-to-ext-js-4-dynamic-loading-and-new-class-system">Dynamic Loading and the New Class System</a></li><li><a href="http://edspencer.net/2011/01/classes-in-ext-js-4-under-the-hood.html">Classes in Ext JS 4: Under the Hood</a></li><li><a href="http://edspencer.net/2011/01/ext-js-4-the-class-definition-pipeline.html">The Class Defition Pipeline</a></li></ul>
308
309 <h2>This guide is a work in progress.</h2>
310
311 <p>Please check back soon</p></div></div></div></div></body></html>