3 This file is part of Ext JS 4
5 Copyright (c) 2011 Sencha Inc
7 Contact: http://www.sencha.com/contact
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.
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
16 * @class Ext.app.Controller
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:
21 * Ext.define('MyApp.controller.Users', {
22 * extend: 'Ext.app.Controller',
25 * console.log('Initialized Users! This happens before the Application launch function is called');
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.
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:
38 * Ext.define('MyApp.controller.Users', {
39 * extend: 'Ext.app.Controller',
43 * 'viewport > panel': {
44 * render: this.onPanelRendered
49 * onPanelRendered: function() {
50 * console.log('The panel was rendered');
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.
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.
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:
69 * Ext.define('MyApp.controller.Users', {
70 * extend: 'Ext.app.Controller',
82 * click: this.refreshGrid
87 * refreshGrid: function() {
88 * this.getList().store.load();
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'.
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'.
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).
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.
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.
115 * <u>Generated getter methods</u>
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:
120 * Ext.define('MyApp.controller.Users', {
121 * extend: 'Ext.app.Controller',
124 * stores: ['AllUsers', 'AdminUsers'],
127 * var User = this.getUserModel(),
128 * allUsers = this.getAllUsersStore();
130 * var ed = new User({name: 'Ed'});
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
141 * <u>Further Reading</u>
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.
146 * @docauthor Ed Spencer
148 Ext.define('Ext.app.Controller', {
151 observable: 'Ext.util.Observable'
155 * @cfg {String} id The id of this controller. You can use this id when dispatching.
158 onClassExtended: function(cls, data) {
159 var className = Ext.getClassName(cls),
160 match = className.match(/^(.*)\.controller\./);
162 if (match !== null) {
163 var namespace = Ext.Loader.getPrefix(className) || match[1],
164 onBeforeClassCreated = data.onBeforeClassCreated,
166 modules = ['model', 'view', 'store'],
169 data.onBeforeClassCreated = function(cls, data) {
171 items, j, subLn, item;
173 for (i = 0,ln = modules.length; i < ln; i++) {
176 items = Ext.Array.from(data[module + 's']);
178 for (j = 0,subLn = items.length; j < subLn; j++) {
181 prefix = Ext.Loader.getPrefix(item);
183 if (prefix === '' || prefix === item) {
184 requires.push(namespace + '.' + module + '.' + item);
192 Ext.require(requires, Ext.Function.pass(onBeforeClassCreated, arguments, this));
198 * Creates new Controller.
199 * @param {Object} config (optional) Config object.
201 constructor: function(config) {
202 this.mixins.observable.constructor.call(this, config);
204 Ext.apply(this, config || {});
206 this.createGetters('model', this.models);
207 this.createGetters('store', this.stores);
208 this.createGetters('view', this.views);
216 init: function(application) {},
218 onLaunch: function(application) {},
220 createGetters: function(type, refs) {
221 type = Ext.String.capitalize(type);
222 Ext.Array.each(refs, function(ref) {
224 parts = ref.split('.');
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);
233 this[fn] = Ext.Function.pass(this['get' + type], [ref], this);
235 // Execute it right away
241 ref: function(refs) {
243 refs = Ext.Array.from(refs);
244 Ext.Array.each(refs, function(info) {
246 fn = 'get' + Ext.String.capitalize(ref);
248 me[fn] = Ext.Function.pass(me.getRef, [ref, info], me);
253 getRef: function(ref, info, config) {
254 this.refCache = this.refCache || {};
256 config = config || {};
258 Ext.apply(info, config);
260 if (info.forceCreate) {
261 return Ext.ComponentManager.create(info, 'component');
265 selector = info.selector,
266 cached = me.refCache[ref];
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');
274 cached.on('beforedestroy', function() {
275 me.refCache[ref] = null;
284 * Adds listeners to components selected via {@link Ext.ComponentQuery}. Accepts an
285 * object containing component paths mapped to a hash of listener functions.
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.
290 * Ext.define('AM.controller.Users', {
293 * 'useredit button[action=save]': {
294 * click: this.updateUser
299 * updateUser: function(button) {
300 * console.log('clicked the Save button');
304 * See {@link Ext.ComponentQuery} for more information on component selectors.
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
310 control: function(selectors, listeners) {
311 this.application.control(selectors, listeners, this);
315 * Returns a reference to a {@link Ext.app.Controller controller} with the given name
316 * @param name {String}
318 getController: function(name) {
319 return this.application.getController(name);
323 * Returns a reference to a {@link Ext.data.Store store} with the given name
324 * @param name {String}
326 getStore: function(name) {
327 return this.application.getStore(name);
331 * Returns a reference to a {@link Ext.data.Model Model} with the given name
332 * @param name {String}
334 getModel: function(model) {
335 return this.application.getModel(model);
339 * Returns a reference to a view with the given name
340 * @param name {String}
342 getView: function(view) {
343 return this.application.getView(view);