View Controllers
Like the ViewModel, Ext JS 5 introduces a ViewController class. The ViewController class can be used instead of the traditional Controller class. The Controller classes manage the views and bind the events with the views. This can become a bit tedious if the application grows as a single view can be managed by multiple controllers and a single controller can also manage multiple views.
ViewControllers solve this problem by reversing the role played by the controllers.
- The View components will specify the ViewControllers that will manage them.
- The View components define a reference that the ViewControllers can use to handle them
Let’s create a textfield and a button. The button’s click event will be handled by a ViewController. The ViewController accesses the textfield using the reference and fetches the entered value.
Ext.create('Ext.panel.Panel', { controller : "signup", items : [ { xtype : "textfield", emptyText : "User Name", reference : "username" }, { xtype : "button", text : "Sign up", listeners : { click : "onSignupButtonClicked" } } ] });
The Panel is linked to a controller called signup which is a ViewController that we’ll define later. The User Name textfield has a reference username that the ViewController will use. The click event of the button is handled by the onSignupButtonClicked function defined in the ViewController. And here’s the ViewController.
Ext.define('SignupController', { extend: 'Ext.app.ViewController', alias: 'controller.signup', onSignupButtonClicked : function(){ var userName = this.lookupReference("username"); console.log(userName.getValue()); } });
You can read more about the ViewController in http://docs.sencha.com/extjs/5.0.0/application_architecture/view_controllers.html.