|
il y a 2 ans | |
---|---|---|
.. | ||
README.js | il y a 2 ans | |
README.md | il y a 2 ans | |
doubleClickHandler.png | il y a 2 ans | |
firstControllerListener.png | il y a 2 ans | |
firstView.png | il y a 2 ans | |
folderStructure.png | il y a 2 ans | |
icon.png | il y a 2 ans | |
loadedForm.png | il y a 2 ans | |
panelView.png | il y a 2 ans | |
postUpdatesToServer.png | il y a 2 ans | |
saveHandler.png | il y a 2 ans | |
updatedGridRecord.png | il y a 2 ans |
Contents
\n\nLarge client side applications have always been hard to write, hard to\norganize and hard to maintain. They tend to quickly grow out of\ncontrol as you add more functionality and developers to a project. Ext\nJS 4 comes with a new application architecture that not only organizes\nyour code but reduces the amount you have to write.
\n\nOur application architecture follows an MVC-like pattern with Models\nand Controllers being introduced for the first time. There are many\nMVC architectures, most of which are slightly different from one\nanother. Here's how we define ours:
\n\nModel is a collection of fields and their data (e.g. a User\nmodel with username and password fields). Models know how to\npersist themselves through the data package, and can be linked to\nother models through associations. Models work a lot like the Ext\nJS 3 Record class, and are normally used with\nStores to present data into grids and\nother components
View is any type of component - grids, trees and panels are all\nviews.
Controllers are special places to put all of the code that makes\nyour app work - whether that's rendering views, instantiating\nModels, or any other app logic.
In this guide we'll be creating a very simple application that manages\nUser data. By the end you will know how to put simple applications\ntogether using the new Ext JS 4 application architecture.
\n\nThe application architecture is as much about providing structure and\nconsistency as it is about actual classes and framework\ncode. Following the conventions unlocks a number of important\nbenefits:
\n\nExt JS 4 applications follow a unified directory structure that is the\nsame for every app. Please check out the Getting Started\nguide for a detailed explanation on the\nbasic file structure of an application. In MVC layout, all classes are\nplaced into the app/
folder, which in turn contains sub-folders to\nnamespace your models, views, controllers and stores. Here is how the\nfolder structure for the simple example app will look when we're done:
In this example, we are encapsulating the whole application inside one\nfolder called 'account_manager
'. Essential files from the Ext JS 4\nSDK are wrapped inside ext-4/
\nfolder. Hence the content of our index.html
looks like this:
<html>\n<head>\n <title>Account Manager</title>\n\n <link rel=\"stylesheet\" type=\"text/css\" href=\"ext-4/resources/css/ext-all.css\">\n\n <script type=\"text/javascript\" src=\"ext-4/ext-debug.js\"></script>\n\n <script type=\"text/javascript\" src=\"app.js\"></script>\n</head>\n<body></body>\n</html>\n
\n\napp.js
Every Ext JS 4 application starts with an instance of Application class. The Application contains\nglobal settings for your application (such as the app's name), as well\nas maintains references to all of the models, views and controllers\nused by the app. An Application also contains a launch function, which\nis run automatically when everything is loaded.
\n\nLet's create a simple Account Manager app that will help us manage\nUser accounts. First we need to pick a global namespace for this\napplication. All Ext JS 4 applications should only use a single global\nvariable, with all of the application's classes nested inside\nit. Usually we want a short global variable so in this case we're\ngoing to use \"AM\":
\n\nExt.application({\n requires: ['Ext.container.Viewport'],\n name: 'AM',\n\n appFolder: 'app',\n\n launch: function() {\n Ext.create('Ext.container.Viewport', {\n layout: 'fit',\n items: [\n {\n xtype: 'panel',\n title: 'Users',\n html : 'List of users will go here'\n }\n ]\n });\n }\n});\n
\n\nThere are a few things going on here. First we invoked\nExt.application
to create a new instance of Application class, to\nwhich we passed the name 'AM'
. This automatically sets up a global\nvariable AM
for us, and registers the namespace to Ext.Loader
,\nwith the corresponding path of 'app
' set via the appFolder
config\noption. We also provided a simple launch function that just creates a\nViewport which contains a single\nPanel that will fill the screen.
Controllers are the glue that binds an application together. All they\nreally do is listen for events (usually from views) and take some\nactions. Continuing our Account Manager application, lets create a\ncontroller. Create a file called app/controller/Users.js
and add\nthe following code:
Ext.define('AM.controller.Users', {\n extend: 'Ext.app.Controller',\n\n init: function() {\n console.log('Initialized Users! This happens before the Application launch function is called');\n }\n});\n
\n\nNow lets add our newly created Users controller to the application\nconfig in app.js:
\n\nExt.application({\n ...\n\n controllers: [\n 'Users'\n ],\n\n ...\n});\n
\n\nWhen we load our application by visiting index.html
inside a\nbrowser, the Users
controller is automatically loaded (because we\nspecified it in the Application definition above), and its init
\nfunction is called just before the Application's launch
function.
The init
function is a great place to set up how your controller\ninteracts with the view, and is usually used in conjunction with\nanother Controller function - control. The control
function makes it easy to listen to events on\nyour view classes and take some action with a handler function. Let's\nupdate our Users
controller to tell us when the panel is rendered:
Ext.define('AM.controller.Users', {\n extend: 'Ext.app.Controller',\n\n init: function() {\n this.control({\n 'viewport > panel': {\n render: this.onPanelRendered\n }\n });\n },\n\n onPanelRendered: function() {\n console.log('The panel was rendered');\n }\n});\n
\n\nWe've updated the init
function to use this.control
to set up\nlisteners on views in our application. The control
function uses the\nnew ComponentQuery engine to quickly and easily get references to\ncomponents on the page. If you are not familiar with ComponentQuery\nyet, be sure to check out the ComponentQuery\ndocumentation for a full explanation. In brief though, it allows us\nto pass a CSS-like selector that will find every matching component on\nthe page.
In our init function above we supplied 'viewport > panel'
, which\ntranslates to \"find me every Panel that is a direct child of a\nViewport\". We then supplied an object that maps event names (just\nrender
in this case) to handler functions. The overall effect is\nthat whenever any component that matches our selector fires a render
\nevent, our onPanelRendered
function is called.
When we run our application now we see the following:
\n\nNot exactly the most exciting application ever, but it shows how easy\nit is to get started with organized code. Let's flesh the app out a\nlittle now by adding a grid.
\n\nUntil now our application has only been a few lines long and only\ninhabits two files - app.js
and app/controller/Users.js
. Now that\nwe want to add a grid showing all of the users in our system, it's\ntime to organize our logic a little better and start using views.
A View is nothing more than a Component, usually defined as a subclass\nof an Ext JS component. We're going to create our Users grid now by\ncreating a new file called app/view/user/List.js
and putting the\nfollowing into it:
Ext.define('AM.view.user.List' ,{\n extend: 'Ext.grid.Panel',\n alias: 'widget.userlist',\n\n title: 'All Users',\n\n initComponent: function() {\n this.store = {\n fields: ['name', 'email'],\n data : [\n {name: 'Ed', email: 'ed@sencha.com'},\n {name: 'Tommy', email: 'tommy@sencha.com'}\n ]\n };\n\n this.columns = [\n {header: 'Name', dataIndex: 'name', flex: 1},\n {header: 'Email', dataIndex: 'email', flex: 1}\n ];\n\n this.callParent(arguments);\n }\n});\n
\n\nOur View class is nothing more than a normal class. In this case we\nhappen to extend the Grid Component and set up an alias so that we can\nuse it as an xtype (more on that in a moment). We also passed in the\nstore configuration and the columns that the grid should render.
\n\nNext we need to add this view to our Users
controller. Because we\nset an alias using the special 'widget.'
format, we can use\n'userlist' as an xtype now, just like we had used 'panel'
\npreviously.
Ext.define('AM.controller.Users', {\n extend: 'Ext.app.Controller',\n\n views: [\n 'user.List'\n ],\n\n init: ...\n\n onPanelRendered: ...\n});\n
\n\nAnd then render it inside the main viewport by modifying the launch\nmethod in app.js
to:
Ext.application({\n ...\n\n launch: function() {\n Ext.create('Ext.container.Viewport', {\n layout: 'fit',\n items: {\n xtype: 'userlist'\n }\n });\n }\n});\n
\n\nThe only other thing to note here is that we specified 'user.List'
\ninside the views array. This tells the application to load that file\nautomatically so that we can use it when we launch. The application\nuses Ext JS 4's new dynamic loading system to automatically pull this\nfile from the server. Here's what we see when we refresh the page now:
Note that our onPanelRendered
function is still being called. This\nis because our grid class still matches the 'viewport > panel'
\nselector. The reason for this is that our class extends Grid, which in\nturn extends Panel.
At the moment, the listeners we add to this selector will actually be\ncalled for every Panel or Panel subclass that is a direct child of the\nviewport, so let's tighten that up a bit using our new xtype. While\nwe're at it, let's instead listen for double clicks on rows in the\ngrid so that we can later edit that User:
\n\nExt.define('AM.controller.Users', {\n extend: 'Ext.app.Controller',\n\n views: [\n 'user.List'\n ],\n\n init: function() {\n this.control({\n 'userlist': {\n itemdblclick: this.editUser\n }\n });\n },\n\n editUser: function(grid, record) {\n console.log('Double clicked on ' + record.get('name'));\n }\n});\n
\n\nNote that we changed the ComponentQuery selector (to simply\n'userlist'
), the event name (to 'itemdblclick'
) and the handler\nfunction name (to 'editUser'
). For now we're just logging out the\nname of the User we double clicked:
Logging to the console is all well and good but we really want to edit\nour Users. Let's do that now, starting with a new view in\napp/view/user/Edit.js
:
Ext.define('AM.view.user.Edit', {\n extend: 'Ext.window.Window',\n alias: 'widget.useredit',\n\n title: 'Edit User',\n layout: 'fit',\n autoShow: true,\n\n initComponent: function() {\n this.items = [\n {\n xtype: 'form',\n items: [\n {\n xtype: 'textfield',\n name : 'name',\n fieldLabel: 'Name'\n },\n {\n xtype: 'textfield',\n name : 'email',\n fieldLabel: 'Email'\n }\n ]\n }\n ];\n\n this.buttons = [\n {\n text: 'Save',\n action: 'save'\n },\n {\n text: 'Cancel',\n scope: this,\n handler: this.close\n }\n ];\n\n this.callParent(arguments);\n }\n});\n
\n\nAgain we're just defining a subclass of an existing component - this\ntime Ext.window.Window
. Once more we used initComponent
to specify\nthe complex objects items
and buttons
. We used a 'fit'
layout\nand a form as the single item, which contains fields to edit the name\nand the email address. Finally we created two buttons, one which just\ncloses the window, and the other that will be used to save our\nchanges.
All we have to do now is add the view to the controller, render it and\nload the User into it:
\n\nExt.define('AM.controller.Users', {\n extend: 'Ext.app.Controller',\n\n views: [\n 'user.List',\n 'user.Edit'\n ],\n\n init: ...\n\n editUser: function(grid, record) {\n var view = Ext.widget('useredit');\n\n view.down('form').loadRecord(record);\n }\n});\n
\n\nFirst we created the view using the convenient method Ext.widget
,\nwhich is equivalent to Ext.create('widget.useredit')
. Then we\nleveraged ComponentQuery once more to quickly get a reference to the\nedit window's form. Every component in Ext JS 4 has a down
function,\nwhich accepts a ComponentQuery selector to quickly find any child\ncomponent.
Double clicking a row in our grid now yields something like this:
\n\nNow that we have our edit form it's almost time to start editing our\nusers and saving those changes. Before we do that though, we should\nrefactor our code a little.
\n\nAt the moment the AM.view.user.List
component creates a Store\ninline. This works well but we'd like to be able to reference that\nStore elsewhere in the application so that we can update the data in\nit. We'll start by breaking the Store out into its own file -\napp/store/Users.js
:
Ext.define('AM.store.Users', {\n extend: 'Ext.data.Store',\n fields: ['name', 'email'],\n data: [\n {name: 'Ed', email: 'ed@sencha.com'},\n {name: 'Tommy', email: 'tommy@sencha.com'}\n ]\n});\n
\n\nNow we'll just make 2 small changes - first we'll ask our Users
\ncontroller to include this Store when it loads:
Ext.define('AM.controller.Users', {\n extend: 'Ext.app.Controller',\n stores: [\n 'Users'\n ],\n ...\n});\n
\n\nthen we'll update app/view/user/List.js
to simply reference the\nStore by id:
Ext.define('AM.view.user.List' ,{\n extend: 'Ext.grid.Panel',\n alias: 'widget.userlist',\n title: 'All Users',\n\n // we no longer define the Users store in the `initComponent` method\n store: 'Users',\n\n initComponent: function() {\n\n this.columns = [\n ...\n});\n
\n\nBy including the stores that our Users
controller cares about in its\ndefinition they are automatically loaded onto the page and given a\nstoreId, which makes them really easy\nto reference in our views (by simply configuring store: 'Users'
in\nthis case).
At the moment we've just defined our fields ('name'
and 'email'
)\ninline on the store. This works well enough but in Ext JS 4 we have a\npowerful Ext.data.Model
class that we'd like to take advantage of\nwhen it comes to editing our Users. We'll finish this section by\nrefactoring our Store to use a Model, which we'll put in\napp/model/User.js
:
Ext.define('AM.model.User', {\n extend: 'Ext.data.Model',\n fields: ['name', 'email']\n});\n
\n\nThat's all we need to do to define our Model. Now we'll just update\nour Store to reference the Model name instead of providing fields\ninline...
\n\nExt.define('AM.store.Users', {\n extend: 'Ext.data.Store',\n model: 'AM.model.User',\n\n data: [\n {name: 'Ed', email: 'ed@sencha.com'},\n {name: 'Tommy', email: 'tommy@sencha.com'}\n ]\n});\n
\n\nAnd we'll ask the Users
controller to get a reference to the User
\nmodel too:
Ext.define('AM.controller.Users', {\n extend: 'Ext.app.Controller',\n stores: ['Users'],\n models: ['User'],\n ...\n});\n
\n\nOur refactoring will make the next section easier but should not have\naffected the application's current behavior. If we reload the page now\nand double click on a row we see that the edit User window still\nappears as expected. Now it's time to finish the editing\nfunctionality:
\n\nNow that we have our users grid loading data and opening an edit\nwindow when we double click each row, we'd like to save the changes\nthat the user makes. The Edit User window that the defined above\ncontains a form (with fields for name and email), and a save\nbutton. First let's update our controller's init function to listen\nfor clicks to that save button:
\n\nExt.define('AM.controller.Users', {\n ...\n init: function() {\n this.control({\n 'viewport > userlist': {\n itemdblclick: this.editUser\n },\n 'useredit button[action=save]': {\n click: this.updateUser\n }\n });\n },\n ...\n updateUser: function(button) {\n console.log('clicked the Save button');\n }\n ...\n});\n
\n\nWe added a second ComponentQuery selector to our this.control
call -\nthis time 'useredit button[action=save]'
. This works the same way as\nthe first selector - it uses the 'useredit'
xtype that we defined\nabove to focus in on our edit user window, and then looks for any\nbuttons with the 'save'
action inside that window. When we defined\nour edit user window we passed {action: 'save'}
to the save button,\nwhich gives us an easy way to target that button.
We can satisfy ourselves that the updateUser
function is called when\nwe click the Save button:
Now that we've seen our handler is correctly attached to the Save\nbutton's click event, let's fill in the real logic for the\nupdateUser
function. In this function we need to get the data out of\nthe form, update our User with it and then save that back to the Users\nstore we created above. Let's see how we might do that:
updateUser: function(button) {\n var win = button.up('window'),\n form = win.down('form'),\n record = form.getRecord(),\n values = form.getValues();\n\n record.set(values);\n win.close();\n}\n
\n\nLet's break down what's going on here. Our click event gave us a\nreference to the button that the user clicked on, but what we really\nwant is access to the form that contains the data and the window\nitself. To get things working quickly we'll just use ComponentQuery\nagain here, first using button.up('window')
to get a reference to\nthe Edit User window, then win.down('form')
to get the form.
After that we simply fetch the record that's currently loaded into the\nform and update it with whatever the user has typed into the\nform. Finally we close the window to bring attention back to the\ngrid. Here's what we see when we run our app again, change the name\nfield to 'Ed Spencer'
and click save:
Easy enough. Let's finish this up now by making it interact with our\nserver side. At the moment we are hard coding the two User records\ninto the Users Store, so let's start by reading those over AJAX\ninstead:
\n\nExt.define('AM.store.Users', {\n extend: 'Ext.data.Store',\n model: 'AM.model.User',\n autoLoad: true,\n\n proxy: {\n type: 'ajax',\n url: 'data/users.json',\n reader: {\n type: 'json',\n root: 'users',\n successProperty: 'success'\n }\n }\n});\n
\n\nHere we removed the 'data'
property and replaced it with a\nProxy. Proxies are the way to load and\nsave data from a Store or a Model in Ext JS 4. There are proxies for\nAJAX, JSON-P and HTML5 localStorage among others. Here we've used a\nsimple AJAX proxy, which we've told to load data from the url\n'data/users.json'
.
We also attached a Reader to the\nProxy. The reader is responsible for decoding the server response into\na format the Store can understand. This time we used a JSON Reader, and specified the root and\nsuccessProperty
configurations. Finally we'll create our\ndata/users.json
file and paste our previous data into it:
{\n \"success\": true,\n \"users\": [\n {\"id\": 1, \"name\": 'Ed', \"email\": \"ed@sencha.com\"},\n {\"id\": 2, \"name\": 'Tommy', \"email\": \"tommy@sencha.com\"}\n ]\n}\n
\n\nThe only other change we made to the Store was to set autoLoad
to\ntrue
, which means the Store will ask its Proxy to load that data\nimmediately. If we refresh the page now we'll see the same outcome as\nbefore, except that we're now no longer hard coding the data into our\napplication.
The last thing we want to do here is send our changes back to the\nserver. For this example we're just using static JSON files on the\nserver side so we won't see any database changes but we can at least\nverify that everything is plugged together correctly. First we'll make\na small change to our new proxy to tell it to send updates back to a\ndifferent url:
\n\nproxy: {\n type: 'ajax',\n api: {\n read: 'data/users.json',\n update: 'data/updateUsers.json'\n },\n reader: {\n type: 'json',\n root: 'users',\n successProperty: 'success'\n }\n}\n
\n\nWe're still reading the data from users.json
but any updates will be\nsent to updateUsers.json
. This is just so we know things are working\nwithout overwriting our test data. After updating a record, the\nupdateUsers.json
file just contains {\"success\": true}
. Since it is\nupdated through a HTTP POST command, you may have to create an empty\nfile to avoid receiving a 404 error.
The only other change we need to make is to tell our Store to\nsynchronize itself after editing, which we do by adding one more line\ninside the updateUser function, which now looks like this:
\n\nupdateUser: function(button) {\n var win = button.up('window'),\n form = win.down('form'),\n record = form.getRecord(),\n values = form.getValues();\n\n record.set(values);\n win.close();\n // synchronize the store after editing the record\n this.getUsersStore().sync();\n}\n
\n\nNow we can run through our full example and make sure that everything\nworks. We'll edit a row, hit the Save button and see that the request\nis correctly sent to updateUser.json
The newly introduced Sencha SDK Tools (download\nhere) makes\ndeployment of any Ext JS 4 application easier than ever. The tools\nallows you to generate a manifest of all dependencies in the form of a\nJSB3 (JSBuilder file format) file, and create a minimal custom build\nof just what your application needs within minutes.
\n\nPlease refer to the Getting Started guide\nfor detailed instructions.
\n\nWe've created a very simple application that manages User data and\nsends any updates back to the server. We started out simple and\ngradually refactored our code to make it cleaner and more\norganized. At this point it's easy to add more functionality to our\napplication without creating spaghetti code. The full source code for\nthis application can be found in the Ext JS 4 SDK download, inside the\nexamples/app/simple folder.
\n"});