-
Notifications
You must be signed in to change notification settings - Fork 56
ViewController
A ViewController
is a lightweight controller for a view. It is responsible for managing the state of the view and its child components, listening for events dispatched by the view and its child components in response to user gestures, and delegating work to injected business services (such as Stores, Models, Service classes, etc.).
The key idea behind a ViewController
is to make your views as "dumb" as possible. You know all those inline event listeners and all that view-specific logic that typically complicates your view components? Rip it out and move it into a ViewController. Your fellow developers and the folks who may later have to maintain your code will have big smiles on their faces when they see the nice, clean view components you leave behind. It also makes it much easier to test view-related logic because it's wrapped up in a separate class.
To start with, let's take a look at a very basic ViewController
:
Ext.define("DeftQuickStart.controller.MainController", {
extend: "Deft.mvc.ViewController",
init: function() {
return this.callParent(arguments);
}
});
There's obviously nothing very interesting going on here yet. Don't worry, we'll get to the cool stuff on the next few pages. For now, let's look at how we can associate this ViewController with a view:
Ext.define( "DeftQuickStart.view.MyPanel", {
extend: "Ext.panel.Panel",
requires: [ "DeftQuickStart.controller.MainController" ],
controller: "DeftQuickStart.controller.MainController",
width: 300,
title: "My Panel",
items: [{
xtype: "button",
itemId: "myButton",
text: "Click Me"
}]
});
This should look pretty typical. The only unusual thing is the controller
property. This is where we specify which ViewController
is associated with the view.
Note for Sencha Cmd Users: Deft JS dynamically requires the ViewController class for you. Unfortunately, Sencha Cmd can't handle this dynamic behavior. So if you use Cmd, you'll need to add a
requires
entry for your ViewController class.
We should mention here that unlike Sencha's Ext.app.Controller
, DeftJS ViewControllers are not singletons. That means each instance of a view will get its own instance of its associated ViewController
. It's automatically created when the view is created, and it's automatically destroyed when the view is destroyed. As you can imagine, this makes it a lot easier to maintain the state of a specific view and deal with view events.
Let's start making things interesting by bringing the Deft JS IoC container back into the mix and taking a look at how we can inject dependencies into our objects.