Extjs application architecture design (2)

Source: Internet
Author: User

Original article: http://www.sencha.com/learn/architecting-your-app-in-ext-js-4-part-2/

In extjs application architecture design, we explored how to use extjs to build a Pandora-style application.Program. We adopt the MVC Architecture and apply it to a complicated user interface with multiple views and models. In this articleArticleOn the basis of the architecture, we will continue to explore the control and model design andCodeAnd start to use the Ext. Application and viewprot classes.

Now, let's start writing applications.

Define applications

In extjs 3, The Ext. onready method is the entry for applications and developers to write application architectures. In extjs 4, we introduced a pattern similar to MVC that allows you to follow the best practices when creating an application.

The new MVC package requires the Ext. application method as the entry. This method creates an Ext. App. application instance, and prepares the launch method after the page is ready. Instead of adding features such as creating viewport and setting namespace in Ext. onready.

APP/application. js

Ext. application ({<br/> name: 'panda', <br/> autocreateviewport: True, <br/> launch: function () {<br/> // This is fired as soon as the page is ready <br/>}< br/> });
The configuration item name creates a namespace. All views, models, and store and controllers are named in this namespace. Set autocreateviewport to true. The framework loads the field to the app/View/viewport. js file. In this file, a class named panda. View. viewport is defined. The class name must use the namespace specified by name in the application.

The viewport class

Views in the UI are independent components, so you need to use viewport to bond them. It loads the required views and the configuration items required for their definition to achieve the overall layout of the application. We found that defining views and loading them to viewprot is the fastest way to create the basic structure of the UI.

It is important that the focus of this process is to build a view, rather than a single view itself. Just like carving, you should first create a rough shape of the view and then refine them.

Create construction block

With the previous work, we can now define the view.

APP/View/newstation. js

Ext. define ('panda. view. newstation ', {<br/> extend: 'ext. form. field. combobox', <br/> alias: 'widget. newstation ', <br/> store: 'searchresults', <br/>... more configuration... <br/> });
APP/View/songcontrols. js

Ext. define ('panda. view. songcontrols ', {<br/> extend: 'ext. container ', <br/> alias: 'widget. songcontrols ', <br/>... more configuration... <br/> });
APP/View/stationslist

Ext. define ('panda. view. stationslist ', {<br/> extend: 'ext. grid. panel ', <br/> alias: 'widget. stationslist ', <br/> store: 'stations', <br/>... more configuration... <br/> });
APP/View/recentlyplayedscroller. js

Ext. define ('panda. view. recentlyplayedscroler', {<br/> extend: 'ext. view. view', <br/> alias: 'widget. recentlyplayedscroler', <br/> itemtpl: '<div> </div>', <br/> store: 'centsongs ', <br/>... more configuration... <br/> });
APP/View/songinfo. js

Ext. define ('panda. view. songinfo ', {<br/> extend: 'ext. panel. panel ', <br/> alias: 'widget. songinfo ', <br/> TPL:' <p> about </p> <p> </P> ', <br/>... more configuration... <br/> });
We only list some definitions, and the specific configuration of components will not be discussed in this article.

In the above configuration, we can see that three stores are used, and the names of these stores are defined in the previous article. Now, create a store.

Model and store

Generally, in the initial stage, it is quite useful to use static JSON files containing data as servers. In the future, these static files can be used as a reference for actual server-side dynamic files.

In the current application, to use the station and Song models, you also need to define the two models and bind them to the store of the data component. Each store loads data from the server. The format of the simulated data file is as follows:

Static Data

Data/songs. JSON

{<Br/> 'success': True, <br/> 'results': [<br/> {<br/> 'name': 'blues at sunrise (live) ', <br/> 'artist': 'stevie Ray vaughan', <br/> 'allowe': 'blues at sunrise ', <br/> 'description ': 'description for stevi', <br/> 'played _ date': '1', <br/> 'Station ': 1 <br/> }, <br/>... <br/>] <br/>}
Data/stations. JSON

{< br/> 'success': True, <br/> 'results ': [<br/> {'id': 1, 'played _ date': 4, 'name': 'led zeppelin'}, <br/> {'id ': 2, 'played _ date': 3, 'name': 'The Rolling Stones'}, <br/> {'id': 3, 'played _ date': 2, 'name': 'daft punk'} <br/>] <br/>}
data/searchresults. JSON

{<Br/> 'success': True, <br/> 'results': [<br/> {'id': 1, 'name ': 'led zeppelin'}, <br/> {'id': 2, 'name': 'The Rolling Stones '}, <br/> {'id': 3, 'name': 'daft punk'}, <br/> {'id': 4, 'name': 'John Mayer '}, <br/> {'id ': 5, 'name': 'pete Philly & perquisite '}, <br/> {'id': 6, 'name': 'black star '}, <br/> {'id': 7, 'name': 'macy gray '} <br/>] <br/>}
Model

Models in extjs 4 are similar to those recorded in extjs 3. The main difference is that you can define proxies, verifications, and associations on models. The song code of the model in the application is as follows:

APP/model/song. js

Ext. define ('panda. model. song', {<br/> extend: 'ext. data. model ', <br/> fields: ['id', 'name', 'artlist', 'alipay', 'played _ date', 'Station'], </P> <p> Proxy: {<br/> type: 'ajax ', <br/> URL: 'Data/recentsongs. json', <br/> reader: {<br/> type: 'json', <br/> root: 'results' <br/>}< br/> });
We can see that the proxy is defined in the model. This is a good way to load and save the model instance directly in the model without going through the store. In addition, when multiple stores use this model, you do not need to define a proxy for each store.

Next we will continue to define the station model:

APP/model/station. js

Ext. define ('panda. model. station ', {<br/> extend: 'ext. data. model ', <br/> fields: ['id', 'name', 'played _ date'], </P> <p> Proxy: {<br/> type: 'ajax ', <br/> URL: 'Data/stations. json', <br/> reader: {<br/> type: 'json', <br/> root: 'results' <br/>}< br/> });
Store

In extjs 4, multiple stores can use the same data model, even if the store needs to load data from different sources. In the instance, the model station will be used in the searchresults and stations stores, and they will load data from different locations. Specifically, searchresults returns the search result, while the other returns the user's favorite station. To achieve this, one store needs to override the generation defined in the model.

.

APP/store/searchresults. js

Ext. define ('panda. store. searchresults ', {<br/> extend: 'ext. data. store', <br/> requires: 'panda. model. station ', <br/> model: 'panda. model. station ', </P> <p> // overriding the model's default proxy <br/> Proxy: {<br/> type: 'ajax ', <br/> URL: 'Data/searchresults. json', <br/> reader: {<br/> type: 'json', <br/> root: 'results' <br/>}< br/> });
APP/store/stations. js

Ext. define ('panda. store. stations ', {<br/> extend: 'ext. data. store', <br/> requires: 'panda. model. station ', <br/> model: 'panda. model. station '<br/> });
In the definition of searchresults, the definition of the agent in the station model has been rewritten. When the load method of store is called, its agent will call the agent of store to replace the agent defined in the model.

Of course, you can also use the same interface on the server to return the search results and the user's favorite station. In this way, the two stores can use the default proxy defined in the model, only when loading data, the request parameters are different.

Create recentsongs:

APP/store/recentsongs. js

Ext. define ('panda. store. recentsongs ', {<br/> extend: 'ext. data. store', <br/> model: 'panda. model. song', </P> <p> // make sure to require your model if you are <br/> // not using ext JS 4.0.5 <br/> requires: 'panda. model. song' <br/> });
Note that in extjs of the current version, the model attribute in store cannot automatically create a dependency. Therefore, you need to specify the model through the requires configuration item so that the model can be dynamically loaded.

In addition, according to the Conventions, the store class name must use the plural number, and the model class name must use the singular number.

Add store and model to Application

After defining the model and store, you can add them to the application. Open application. js and add the following code:

APP/application. js

Ext. application ({<br/>... <br/> models: ['Station ', 'song'], <br/> stores: ['stations', 'centsongs ', 'searchresults'] <br/>... <br/> });
Another benefit of using the extjs 4 MVC package is that the application automatically loads the store and model defined in stores and models. After a store is loaded, an instance is created for each store and its name is used as the storeid. In this way, you can use this name to bind it to the data component in the view, such as "searchresults ".

Application Adhesive

At the beginning, you can add the views to the viewport one by one, which makes it easier to debug incorrect view configurations. First build viewport in the panda application:

Ext. Define ('panda. View. viewport', {<br/> extend: 'ext. Container. viewport ',
Generally, the viewport class of the application is extended from Ext. Container. viewport, which makes the application use the available space of the browser as the space of the application.

Requires: [<br/> 'panda. view. newstation ', <br/> 'panda. view. songcontrols ', <br/> 'panda. view. stationslist ', <br/> 'panda. view. recentlyplayedscroler', <br/> 'panda. view. songinfo' <br/>],
Set the viewprot dependency view here. In this way, you can use the name defined by the alias attribute in the view as the value of the xtype configuration item to define the view.

Layout: 'fit ', </P> <p> initcomponent: function () {<br/> This. items = {<br/> xtype: 'panel ', <br/> dockeditems: [{<br/> DOCK: 'top', <br/> xtype: 'toolbar', <br/> Height: 80, <br/> items: [{<br/> xtype: 'newstation', <br/> width: 150 <br/>},{ <br/> xtype: 'songcontrols', <br/> Height: 70, <br/> flex: 1 <br/> }, {<br/> xtype: 'component', <br/> HTML: 'panda <br> Internet radio '<br/>}] <br/>}], <br/> layout :{< br/> type: 'hbox', <br/> align: 'stretch' <br/>}, <br/> items: [{<br/> width: 250, <br/> xtype: 'panel ', <br/> layout: {<br/> type: 'vbox ', <br/> align: 'stretch' <br/>}, <br/> items: [{<br/> xtype: 'stationslist', <br/> flex: 1 <br/>},{ <br/> HTML: 'ad', <br/> Height: 250, <br/> xtype: 'panel '<br/>}] <br/>}, {<br/> xtype: 'Container', <br/> flex: 1, <br/> layout: {<br/> type: 'vbox', <br/> align: 'stretch' <br/>}, <br/> items: [{<br/> xtype: 'recentlyplayedscroler', <br/> Height: 250 <br/>},{ <br/> xtype: 'songinfo', <br/> flex: 1 <br/>}] <br/>}; </P> <p> This. callparent (); <br/>}< br/> });
Because viewport is extended from the container, and the container has no dock items, you must add a panel as the first sub-component of the viewport and use the fit layout to make the Panel have the same size as the viewprot.

In terms of architecture, it is important to note that do not define the layout with specific configurations in the actual view, for example, do not define configuration items such as flex, width, or height, you can easily adjust the overall layout of an application in a certain position, thus increasing the maintainability and flexibility of the architecture.

Application logic

In extjs 3, we usually use the handle of the button, bind the listening time to the sub-component or extend the method to implement the application logic. Then, just as the inline CSS style should not be used in HTML tags, application logic should not be defined in the view. In extjs 4, the Controller provided by the MVC package can respond to the listening events in the view or other controllers and execute the application logic corresponding to these events. This design has the advantage of passing the test.

The first advantage is that the application logic does not need to be bound to the view instance. This means that when the view is instantiated or destroyed, the application logic can continue to process other things, such as synchronizing data.

In extjs 3, there are many nested views, and each of them adds an application logic. When the application logic is moved to the Controller, it is easy to maintain and modify them.

Finally, the controller base class provides some functions to make it easy for the Controller to execute application logic.

Create a controller

Now, with the basic architecture, model, and store configuration of the UI, it is time to define the Controller for the application. We plan to define two controllers, station and song, which are defined as follows:

APP/controller/station. js

Ext. define ('panda. controller. station ', {<br/> extend: 'ext. app. controller ', <br/> init: function () {<br/>... <br/>}, <br/>... <br/> });
APP/controller/song. js

Ext. define ('panda. controller. song', {<br/> extend: 'ext. app. controller ', <br/> init: function () {<br/>... <br/>}, <br/>... <br/> });
After the application contains a controller, the Framework loads the controller when calling the init method. In the init method, you can define monitoring views and application events. In large applications, you sometimes need to load additional controllers at runtime. You can use the getcontroller method to load:

Someaction: function () {<br/> var controller = This. getcontroller ('anothercontroller'); </P> <p> // remember to call the init method manually <br/> controller. init (); <br/>}
When loading additional controllers at runtime, remember to manually call the init method of the loaded controller.

In an instance application, you only need to add the Controller to the array in the controllers configuration item so that the framework can load and initialize the controller.

APP/application. js

Ext. Application ({<br/>... <br/> controllers: ['Station ', 'song'] <br/> });
Define listeners

Now you need to call the control method in the Controller's init method to control the UI parts:

APP/controller/station. js

...Init: Function() {This.Control({'Stationlist': {Selectionchange: This.Onstationselect},'Newstation': {Select: This.Onnewstationselect}});}...

Method control queries the component by the keyword of the object. In the example, the component is queried through the xtypes configuration item in the view. However, to use component query, you must make sure that you can point to the known parts in the UI. For more information about component query, visit here.

Each query is bound to a Listener Configuration object. In each Listener Configuration object, the event name is the keyword of the listener object, and the event is provided by the target component of the query. In the example, the selectionchange event provided by grid (extended in the stationslist view) and the select event provided by ComboBox (expanded from the newstation view) will be used. To find the events of a specific component, you can view the component event section in the API documentation.

The value in the Listener Configuration object is the function executed after the event is triggered. The function will act on the controller itself.

Now add some listeners for the song controller:

APP/controller/song. js

... <Br/> init: function () {<br/> This. control ({<br/> 'centlyplayedscroler': {<br/> selectionchange: This. onsongselect <br/>}< br/>}); </P> <p> This. application. on ({<br/> stationstart: This. onstationstart, <br/> scope: This <br/>}); <br/>}< br/> ..
In addition to listening to selectionchange events in the recentlyplayedscroller view, you also need to listen to application events here. This requires the on method of the application instance. Each control can use this. Application to directly access the application instance.

When many controllers in an application need to listen to the same event, the application event is very useful. Similar to listening to the same view event in each controller, you only need to listen to the view event in one controller to trigger an application-range event. In this way, this event is also monitored by other controllers. In this way, communication between controllers is realized, without understanding or relying on the existence of the other party.

The Controller song needs to know whether the new station has started to update the song scroll bar and Song information.

Now, in the station controller, write the response code when the application event stationstart is triggered:

APP/controller/station. js

... <Br/> onstationselect: function (selmodel, selection) {<br/> This. application. fireevent ('stationstart', Selection [0]); <br/>}< br/>...
In this example, when the stationstart event is triggered, the first selection item in the selectionchange event is passed as a unique parameter to the event.

Summary

In this article, you can understand the basic technology of the application architecture. Of course, this is only a small part. In the next part of the series, we can see some more advanced controller technologies and continue to implement operations in the controller, and add details to the view to complete the panda application.

author: Tommy maintz
Tommy maintz is the original lead of sencha touch. with extensive knowledge of Object Oriented JavaScript and mobile browser idiosyncracies, he pushes the boundaries of what is possible within Mobile browsers. tommy brings a unique view point and an ambitious philosophy to creating engaging user interfaces. his attention to detail drives his desire to make the perfect framework for developers to enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.