Upgrade to ExtJS 4.0.7 - Released 10/19/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 the {@link Ext.ComponentQuery documentation}. 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     /**
159      * @cfg {String[]} models
160      * Array of models to require from AppName.model namespace. For example:
161      * 
162      *     Ext.define("MyApp.controller.Foo", {
163      *         extend: "Ext.app.Controller",
164      *         models: ['User', 'Vehicle']
165      *     });
166      * 
167      * This is equivalent of:
168      * 
169      *     Ext.define("MyApp.controller.Foo", {
170      *         extend: "Ext.app.Controller",
171      *         requires: ['MyApp.model.User', 'MyApp.model.Vehicle']
172      *     });
173      * 
174      */
175
176     /**
177      * @cfg {String[]} views
178      * Array of views to require from AppName.view namespace. For example:
179      * 
180      *     Ext.define("MyApp.controller.Foo", {
181      *         extend: "Ext.app.Controller",
182      *         views: ['List', 'Detail']
183      *     });
184      * 
185      * This is equivalent of:
186      * 
187      *     Ext.define("MyApp.controller.Foo", {
188      *         extend: "Ext.app.Controller",
189      *         requires: ['MyApp.view.List', 'MyApp.view.Detail']
190      *     });
191      * 
192      */
193
194     /**
195      * @cfg {String[]} stores
196      * Array of stores to require from AppName.store namespace. For example:
197      * 
198      *     Ext.define("MyApp.controller.Foo", {
199      *         extend: "Ext.app.Controller",
200      *         stores: ['Users', 'Vehicles']
201      *     });
202      * 
203      * This is equivalent of:
204      * 
205      *     Ext.define("MyApp.controller.Foo", {
206      *         extend: "Ext.app.Controller",
207      *         requires: ['MyApp.store.Users', 'MyApp.store.Vehicles']
208      *     });
209      * 
210      */
211
212     onClassExtended: function(cls, data) {
213         var className = Ext.getClassName(cls),
214             match = className.match(/^(.*)\.controller\./);
215
216         if (match !== null) {
217             var namespace = Ext.Loader.getPrefix(className) || match[1],
218                 onBeforeClassCreated = data.onBeforeClassCreated,
219                 requires = [],
220                 modules = ['model', 'view', 'store'],
221                 prefix;
222
223             data.onBeforeClassCreated = function(cls, data) {
224                 var i, ln, module,
225                     items, j, subLn, item;
226
227                 for (i = 0,ln = modules.length; i < ln; i++) {
228                     module = modules[i];
229
230                     items = Ext.Array.from(data[module + 's']);
231
232                     for (j = 0,subLn = items.length; j < subLn; j++) {
233                         item = items[j];
234
235                         prefix = Ext.Loader.getPrefix(item);
236
237                         if (prefix === '' || prefix === item) {
238                             requires.push(namespace + '.' + module + '.' + item);
239                         }
240                         else {
241                             requires.push(item);
242                         }
243                     }
244                 }
245
246                 Ext.require(requires, Ext.Function.pass(onBeforeClassCreated, arguments, this));
247             };
248         }
249     },
250
251     /**
252      * Creates new Controller.
253      * @param {Object} config (optional) Config object.
254      */
255     constructor: function(config) {
256         this.mixins.observable.constructor.call(this, config);
257
258         Ext.apply(this, config || {});
259
260         this.createGetters('model', this.models);
261         this.createGetters('store', this.stores);
262         this.createGetters('view', this.views);
263
264         if (this.refs) {
265             this.ref(this.refs);
266         }
267     },
268
269     /**
270      * A template method that is called when your application boots. It is called before the
271      * {@link Ext.app.Application Application}'s launch function is executed so gives a hook point to run any code before
272      * your Viewport is created.
273      * 
274      * @param {Ext.app.Application} application
275      * @template
276      */
277     init: function(application) {},
278
279     /**
280      * A template method like {@link #init}, but called after the viewport is created.
281      * This is called after the {@link Ext.app.Application#launch launch} method of Application is executed.
282      * 
283      * @param {Ext.app.Application} application
284      * @template
285      */
286     onLaunch: function(application) {},
287
288     createGetters: function(type, refs) {
289         type = Ext.String.capitalize(type);
290         Ext.Array.each(refs, function(ref) {
291             var fn = 'get',
292                 parts = ref.split('.');
293
294             // Handle namespaced class names. E.g. feed.Add becomes getFeedAddView etc.
295             Ext.Array.each(parts, function(part) {
296                 fn += Ext.String.capitalize(part);
297             });
298             fn += type;
299
300             if (!this[fn]) {
301                 this[fn] = Ext.Function.pass(this['get' + type], [ref], this);
302             }
303             // Execute it right away
304             this[fn](ref);
305         },
306         this);
307     },
308
309     ref: function(refs) {
310         var me = this;
311         refs = Ext.Array.from(refs);
312         Ext.Array.each(refs, function(info) {
313             var ref = info.ref,
314                 fn = 'get' + Ext.String.capitalize(ref);
315             if (!me[fn]) {
316                 me[fn] = Ext.Function.pass(me.getRef, [ref, info], me);
317             }
318         });
319     },
320
321     getRef: function(ref, info, config) {
322         this.refCache = this.refCache || {};
323         info = info || {};
324         config = config || {};
325
326         Ext.apply(info, config);
327
328         if (info.forceCreate) {
329             return Ext.ComponentManager.create(info, 'component');
330         }
331
332         var me = this,
333             selector = info.selector,
334             cached = me.refCache[ref];
335
336         if (!cached) {
337             me.refCache[ref] = cached = Ext.ComponentQuery.query(info.selector)[0];
338             if (!cached && info.autoCreate) {
339                 me.refCache[ref] = cached = Ext.ComponentManager.create(info, 'component');
340             }
341             if (cached) {
342                 cached.on('beforedestroy', function() {
343                     me.refCache[ref] = null;
344                 });
345             }
346         }
347
348         return cached;
349     },
350
351     /**
352      * Adds listeners to components selected via {@link Ext.ComponentQuery}. Accepts an
353      * object containing component paths mapped to a hash of listener functions.
354      *
355      * In the following example the `updateUser` function is mapped to to the `click`
356      * event on a button component, which is a child of the `useredit` component.
357      *
358      *     Ext.define('AM.controller.Users', {
359      *         init: function() {
360      *             this.control({
361      *                 'useredit button[action=save]': {
362      *                     click: this.updateUser
363      *                 }
364      *             });
365      *         },
366      *
367      *         updateUser: function(button) {
368      *             console.log('clicked the Save button');
369      *         }
370      *     });
371      *
372      * See {@link Ext.ComponentQuery} for more information on component selectors.
373      *
374      * @param {String/Object} selectors If a String, the second argument is used as the
375      * listeners, otherwise an object of selectors -> listeners is assumed
376      * @param {Object} listeners
377      */
378     control: function(selectors, listeners) {
379         this.application.control(selectors, listeners, this);
380     },
381
382     /**
383      * Returns instance of a {@link Ext.app.Controller controller} with the given name.
384      * When controller doesn't exist yet, it's created.
385      * @param {String} name
386      * @return {Ext.app.Controller} a controller instance.
387      */
388     getController: function(name) {
389         return this.application.getController(name);
390     },
391
392     /**
393      * Returns instance of a {@link Ext.data.Store Store} with the given name.
394      * When store doesn't exist yet, it's created.
395      * @param {String} name
396      * @return {Ext.data.Store} a store instance.
397      */
398     getStore: function(name) {
399         return this.application.getStore(name);
400     },
401
402     /**
403      * Returns a {@link Ext.data.Model Model} class with the given name.
404      * A shorthand for using {@link Ext.ModelManager#getModel}.
405      * @param {String} name
406      * @return {Ext.data.Model} a model class.
407      */
408     getModel: function(model) {
409         return this.application.getModel(model);
410     },
411
412     /**
413      * Returns a View class with the given name.  To create an instance of the view,
414      * you can use it like it's used by Application to create the Viewport:
415      * 
416      *     this.getView('Viewport').create();
417      * 
418      * @param {String} name
419      * @return {Ext.Base} a view class.
420      */
421     getView: function(view) {
422         return this.application.getView(view);
423     }
424 });
425