Upgrade to ExtJS 4.0.2 - Released 06/09/2011
[extjs.git] / src / app / Controller.js
1 /*
2
3 This file is part of Ext JS 4
4
5 Copyright (c) 2011 Sencha Inc
6
7 Contact:  http://www.sencha.com/contact
8
9 GNU General Public License Usage
10 This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
11
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
13
14 */
15 /**
16  * @class Ext.app.Controller
17  * 
18  * Controllers are the glue that binds an application together. All they really do is listen for events (usually from
19  * views) and take some action. Here's how we might create a Controller to manage Users:
20  * 
21  *     Ext.define('MyApp.controller.Users', {
22  *         extend: 'Ext.app.Controller',
23  * 
24  *         init: function() {
25  *             console.log('Initialized Users! This happens before the Application launch function is called');
26  *         }
27  *     });
28  * 
29  * The init function is a special method that is called when your application boots. It is called before the 
30  * {@link Ext.app.Application Application}'s launch function is executed so gives a hook point to run any code before
31  * your Viewport is created.
32  * 
33  * The init function is a great place to set up how your controller interacts with the view, and is usually used in 
34  * conjunction with another Controller function - {@link Ext.app.Controller#control control}. The control function 
35  * makes it easy to listen to events on your view classes and take some action with a handler function. Let's update
36  * our Users controller to tell us when the panel is rendered:
37  * 
38  *     Ext.define('MyApp.controller.Users', {
39  *         extend: 'Ext.app.Controller',
40  * 
41  *         init: function() {
42  *             this.control({
43  *                 'viewport > panel': {
44  *                     render: this.onPanelRendered
45  *                 }
46  *             });
47  *         },
48  * 
49  *         onPanelRendered: function() {
50  *             console.log('The panel was rendered');
51  *         }
52  *     });
53  * 
54  * We've updated the init function to use this.control to set up listeners on views in our application. The control
55  * function uses the new ComponentQuery engine to quickly and easily get references to components on the page. If you
56  * are not familiar with ComponentQuery yet, be sure to check out THIS GUIDE for a full explanation. In brief though,
57  * it allows us to pass a CSS-like selector that will find every matching component on the page.
58  * 
59  * In our init function above we supplied 'viewport > panel', which translates to "find me every Panel that is a direct
60  * child of a Viewport". We then supplied an object that maps event names (just 'render' in this case) to handler 
61  * functions. The overall effect is that whenever any component that matches our selector fires a 'render' event, our 
62  * onPanelRendered function is called.
63  * 
64  * <u>Using refs</u>
65  * 
66  * One of the most useful parts of Controllers is the new ref system. These use the new {@link Ext.ComponentQuery} to
67  * make it really easy to get references to Views on your page. Let's look at an example of this now:
68  * 
69  *     Ext.define('MyApp.controller.Users', {
70  *         extend: 'Ext.app.Controller',
71  *     
72  *         refs: [
73  *             {
74  *                 ref: 'list',
75  *                 selector: 'grid'
76  *             }
77  *         ],
78  *     
79  *         init: function() {
80  *             this.control({
81  *                 'button': {
82  *                     click: this.refreshGrid
83  *                 }
84  *             });
85  *         },
86  *     
87  *         refreshGrid: function() {
88  *             this.getList().store.load();
89  *         }
90  *     });
91  * 
92  * This example assumes the existence of a {@link Ext.grid.Panel Grid} on the page, which contains a single button to 
93  * refresh the Grid when clicked. In our refs array, we set up a reference to the grid. There are two parts to this - 
94  * the 'selector', which is a {@link Ext.ComponentQuery ComponentQuery} selector which finds any grid on the page and
95  * assigns it to the reference 'list'.
96  * 
97  * By giving the reference a name, we get a number of things for free. The first is the getList function that we use in
98  * the refreshGrid method above. This is generated automatically by the Controller based on the name of our ref, which 
99  * was capitalized and prepended with get to go from 'list' to 'getList'.
100  * 
101  * The way this works is that the first time getList is called by your code, the ComponentQuery selector is run and the
102  * first component that matches the selector ('grid' in this case) will be returned. All future calls to getList will 
103  * use a cached reference to that grid. Usually it is advised to use a specific ComponentQuery selector that will only
104  * match a single View in your application (in the case above our selector will match any grid on the page).
105  * 
106  * Bringing it all together, our init function is called when the application boots, at which time we call this.control
107  * to listen to any click on a {@link Ext.button.Button button} and call our refreshGrid function (again, this will 
108  * match any button on the page so we advise a more specific selector than just 'button', but have left it this way for
109  * simplicity). When the button is clicked we use out getList function to refresh the grid.
110  * 
111  * You can create any number of refs and control any number of components this way, simply adding more functions to 
112  * your Controller as you go. For an example of real-world usage of Controllers see the Feed Viewer example in the 
113  * examples/app/feed-viewer folder in the SDK download.
114  * 
115  * <u>Generated getter methods</u>
116  * 
117  * Refs aren't the only thing that generate convenient getter methods. Controllers often have to deal with Models and 
118  * Stores so the framework offers a couple of easy ways to get access to those too. Let's look at another example:
119  * 
120  *     Ext.define('MyApp.controller.Users', {
121  *         extend: 'Ext.app.Controller',
122  *     
123  *         models: ['User'],
124  *         stores: ['AllUsers', 'AdminUsers'],
125  *     
126  *         init: function() {
127  *             var User = this.getUserModel(),
128  *                 allUsers = this.getAllUsersStore();
129  *     
130  *             var ed = new User({name: 'Ed'});
131  *             allUsers.add(ed);
132  *         }
133  *     });
134  * 
135  * By specifying Models and Stores that the Controller cares about, it again dynamically loads them from the appropriate
136  * locations (app/model/User.js, app/store/AllUsers.js and app/store/AdminUsers.js in this case) and creates getter 
137  * functions for them all. The example above will create a new User model instance and add it to the AllUsers Store.
138  * Of course, you could do anything in this function but in this case we just did something simple to demonstrate the 
139  * functionality.
140  * 
141  * <u>Further Reading</u>
142  * 
143  * For more information about writing Ext JS 4 applications, please see the
144  * [application architecture guide](#/guide/application_architecture). Also see the {@link Ext.app.Application} documentation.
145  * 
146  * @docauthor Ed Spencer
147  */  
148 Ext.define('Ext.app.Controller', {
149
150     mixins: {
151         observable: 'Ext.util.Observable'
152     },
153
154     /**
155      * @cfg {String} id The id of this controller. You can use this id when dispatching.
156      */
157
158     onClassExtended: function(cls, data) {
159         var className = Ext.getClassName(cls),
160             match = className.match(/^(.*)\.controller\./);
161
162         if (match !== null) {
163             var namespace = Ext.Loader.getPrefix(className) || match[1],
164                 onBeforeClassCreated = data.onBeforeClassCreated,
165                 requires = [],
166                 modules = ['model', 'view', 'store'],
167                 prefix;
168
169             data.onBeforeClassCreated = function(cls, data) {
170                 var i, ln, module,
171                     items, j, subLn, item;
172
173                 for (i = 0,ln = modules.length; i < ln; i++) {
174                     module = modules[i];
175
176                     items = Ext.Array.from(data[module + 's']);
177
178                     for (j = 0,subLn = items.length; j < subLn; j++) {
179                         item = items[j];
180
181                         prefix = Ext.Loader.getPrefix(item);
182
183                         if (prefix === '' || prefix === item) {
184                             requires.push(namespace + '.' + module + '.' + item);
185                         }
186                         else {
187                             requires.push(item);
188                         }
189                     }
190                 }
191
192                 Ext.require(requires, Ext.Function.pass(onBeforeClassCreated, arguments, this));
193             };
194         }
195     },
196
197     /**
198      * Creates new Controller.
199      * @param {Object} config (optional) Config object.
200      */
201     constructor: function(config) {
202         this.mixins.observable.constructor.call(this, config);
203
204         Ext.apply(this, config || {});
205
206         this.createGetters('model', this.models);
207         this.createGetters('store', this.stores);
208         this.createGetters('view', this.views);
209
210         if (this.refs) {
211             this.ref(this.refs);
212         }
213     },
214
215     // Template method
216     init: function(application) {},
217     // Template method
218     onLaunch: function(application) {},
219
220     createGetters: function(type, refs) {
221         type = Ext.String.capitalize(type);
222         Ext.Array.each(refs, function(ref) {
223             var fn = 'get',
224                 parts = ref.split('.');
225
226             // Handle namespaced class names. E.g. feed.Add becomes getFeedAddView etc.
227             Ext.Array.each(parts, function(part) {
228                 fn += Ext.String.capitalize(part);
229             });
230             fn += type;
231
232             if (!this[fn]) {
233                 this[fn] = Ext.Function.pass(this['get' + type], [ref], this);
234             }
235             // Execute it right away
236             this[fn](ref);
237         },
238         this);
239     },
240
241     ref: function(refs) {
242         var me = this;
243         refs = Ext.Array.from(refs);
244         Ext.Array.each(refs, function(info) {
245             var ref = info.ref,
246                 fn = 'get' + Ext.String.capitalize(ref);
247             if (!me[fn]) {
248                 me[fn] = Ext.Function.pass(me.getRef, [ref, info], me);
249             }
250         });
251     },
252
253     getRef: function(ref, info, config) {
254         this.refCache = this.refCache || {};
255         info = info || {};
256         config = config || {};
257
258         Ext.apply(info, config);
259
260         if (info.forceCreate) {
261             return Ext.ComponentManager.create(info, 'component');
262         }
263
264         var me = this,
265             selector = info.selector,
266             cached = me.refCache[ref];
267
268         if (!cached) {
269             me.refCache[ref] = cached = Ext.ComponentQuery.query(info.selector)[0];
270             if (!cached && info.autoCreate) {
271                 me.refCache[ref] = cached = Ext.ComponentManager.create(info, 'component');
272             }
273             if (cached) {
274                 cached.on('beforedestroy', function() {
275                     me.refCache[ref] = null;
276                 });
277             }
278         }
279
280         return cached;
281     },
282
283     /**
284      * Adds listeners to components selected via {@link Ext.ComponentQuery}. Accepts an 
285      * object containing component paths mapped to a hash of listener functions. 
286      *
287      * In the following example the `updateUser` function is mapped to to the `click` 
288      * event on a button component, which is a child of the `useredit` component.
289      *
290      *     Ext.define('AM.controller.Users', {
291      *         init: function() {
292      *             this.control({
293      *                 'useredit button[action=save]': {
294      *                     click: this.updateUser
295      *                 }
296      *             });
297      *         },
298      *     
299      *         updateUser: function(button) {
300      *             console.log('clicked the Save button');
301      *         }
302      *     });
303      *
304      * See {@link Ext.ComponentQuery} for more information on component selectors.
305      *
306      * @param {String|Object} selectors If a String, the second argument is used as the 
307      * listeners, otherwise an object of selectors -> listeners is assumed
308      * @param {Object} listeners
309      */
310     control: function(selectors, listeners) {
311         this.application.control(selectors, listeners, this);
312     },
313
314     /**
315      * Returns a reference to a {@link Ext.app.Controller controller} with the given name
316      * @param name {String}
317      */
318     getController: function(name) {
319         return this.application.getController(name);
320     },
321
322     /**
323      * Returns a reference to a {@link Ext.data.Store store} with the given name
324      * @param name {String}
325      */
326     getStore: function(name) {
327         return this.application.getStore(name);
328     },
329
330     /**
331      * Returns a reference to a {@link Ext.data.Model Model} with the given name
332      * @param name {String}
333      */
334     getModel: function(model) {
335         return this.application.getModel(model);
336     },
337
338     /**
339      * Returns a reference to a view with the given name
340      * @param name {String}
341      */
342     getView: function(view) {
343         return this.application.getView(view);
344     }
345 });
346