"Translation" builds a maintainable controller in the Ext JS application

Source: Internet
Author: User

Original: Building maintainable Controllers in Ext JS Apps

    • Hello you had Me
    • You are tearing Me Apart
    • Template we Dont need to be aware of No Stinkin
    • What weve Got here is a failed communicator
    • Smart views are focused and easy to maintain and test

At Emortgage logic, we started using ext JS 4 at the end of 2011. At the time, it was not known how to properly write the Ext JS application, but finally mastered how to get the application to implement the required methods. However, this does not mean that they can be implemented well. The end result is that the application is handled by more than 10 large controller implementations, while the view uses a simple set of configurations. The controller controls everything, but as time goes by, the controller becomes more and more difficult to maintain, which makes people start to wonder if the original code was appropriate.

Finally, we try to make the view a little smarter, and along the way we get a little bit enlightened. Eventually, we finally know how to draw a line between the controller and the view. To illustrate the new findings of our team, I have written the following guidelines. The guide uses a simple way to explain how to disassemble large controllers and replace their logical code for ease of maintenance. This not only facilitates the use of the Ext JS 4 team in the short term, but also facilitates the recent upgrade to the Ext JS 5 View Controller team.

In this article, you will create a small control and a simple view with several requirements, and then separate them by a few steps.

The ultimate goal of this article is to create a controller and a view that implements the following requirements:

    • Provide a form for users to enter preferences
    • Keep preferences to users ' records
    • Update the user's name and preferences and other information
Hello, "You had Me"

View related code

The view that you create will allow the current user to see and update their hobbies, and the view will use the build method, so the subsequent work will be simple.

App/view/hobby.js

Ext.define (' Example.view.Hobby ', {extend:' Ext.form.Panel ', alias:' Widget.hobbyview ', InitComponent: function () {        varme = This;        Me.items = Me.builditems (); Me.callparent (arguments); }, Builditems: function () {        return[{xtype:' TextField ', Name:' Favoritehobby '}, {xtype:' button ', ItemId:' Save ', Text:' Save '}, {xtype:' component ', ItemId:' Hobbytpl ', TPL:' {name}\ ' s favorite hobby is {favoritehobby} '}        ]; }});

Below, the controller is created to manage the view:

App/controller/hobby.js

Ext.define (' Example.controller.Hobby ', {extend:' Ext.app.Controller 'Init: function () {         This. Control ({' Hobbyview button#save ': {click: This. Onsavebuttonclick}}); }, Onsavebuttonclick: function (button) {        varform = Button.up (' form '), values = Form.getvalues (), user;//We'll assume the application provides a to get the currently logged-in user.user = This. Getapplication (). Getcurrentuser ();        User.set (values);        User.save (); Form.down (' #hobbyTpl '). Update ({Name:user.get (' Name '), Favoritehobby:values.    Favoritehobby}); }});

Although it is a very simple controller, it knows that the view has a problem with it.

Controller to know:

The view has a button that Itemid to save
button is a sub-component of the form
How to get values from a view's form
The form has a itemid for hobbytpl, how do I update it?
The form does not know the concept of user

Everything in the controller depends entirely on the view's Save button and the structure of the view itself, which causes the controller and view to be tightly coupled, for example, if the Save button is outside the form component, the controller has to rewrite it. In addition, if the components of the Itemid are HOBBYTPL changed, the controller also needs to make corresponding changes. Any minor changes in the view can cause problems for the controller.

You are tearing Me Apart

View related code

Now that you can be aware of some of the controller's problems, here's how to solve these problems. The first is to have the view associated with the user.

App/view/hobby.js

Ext.define(‘Example.view.Hobby‘, {    // ...    function (record) {        this.userRecord = record;    },    function () {        returnthis.userRecord;    }    // ...});

By setting some methods to associate users, it is easy to adjust the view method without modifying the controller. With these additional items, you can let the view follow user records by passing an instance or later calling the Binduser method. This way, you can also get a bound user, and the controller does not need to know too much.

Next, let the controller allow the view to manage user records and update the data.

App/controller/hobby.js

Ext.define(‘Example.controller.Hobby‘, {    // ...    function (button) {        var form = button.up(‘form‘),            values = form.getValues(),            user = form.getUser();        user.set(values);        user.save();        form.down(‘#hobbyTpl‘).update({            Name: user.get(‘Name‘),            FavoriteHobby: values.FavoriteHobby        });    }});

Very good, but there is one thing in the list is not done, that is the controller or to understand the structure of the view, now to do is to make it more flexible.

Update the checklist below:

Controller knows

    • The view has a button that Itemid to save
    • button is a sub-component of the form
    • How to get values from a view's form
    • The form has a itemid for hobbytpl, how do I update it?
    • The form does not know the concept of user
Template? We Don ' t need [to be aware of] No stinkin templates

View related code

The view is always wondering why the controller can't focus on its own business logic, which can be left out of mind by removing the template's content.

The view wants its template to be updated when the Save button is clicked, in order to achieve this goal, you need to add event handling.

App/view/hobby.js

Ext.define (' Example.view.Hobby ', {// ...Onsaveclick: function () {        varme = This, values = Me.getvalues (), user = Me.getuser (); Me.down (' #hobbyTpl '). Update ({Name:user.get (' Name '), Favoritehobby:values.    Favoritehobby}); }, Builditems: function () {        varme = This;return[{xtype:' TextField ', Name:' Favoritehobby '}, {xtype:' button ', ItemId:' Save ', Text:' Save ', listeners: {Click:me.onSaveClick, scope:me} }, {xtype:' component ', ItemId:' Hobbytpl ', TPL:' {name}\ ' s favorite hobby is {favoritehobby} '}        ]; }});

The view now handles more view transactions, and the controller can be simpler.

App/controller/hobby.js

Ext.define(‘Example.controller.Hobby‘, {    // ...    function (button) {        var form = button.up(‘form‘),            values = form.getValues(),            user = form.getUser();        user.set(values);        user.save();    }});

Unfortunately, the controller can still see a lot of view components, but at least one thing is missing from the list:

Controller knows

    • The view has a button that Itemid to save
    • button is a sub-component of the form
    • How to get values from a view's form
    • The form has a itemid for hobbytpl, how do I update it?
    • The form does not know the concept of user
What do We ' ve Got here is a failed communicator

View related code

Now it's time to solve the rest of the problem, which requires events to communicate between the view and the controller. The controller only needs to know that the view is getting the data, and that the data is saved.

In the Onsaveclick event, all the data required by the controller has been aggregated in the view, so there is only one event to start here.

App/view/hobby.js

Ext.define(‘Example.view.Hobby‘, {    // ...    function () {        varthis,            values = me.getValues(),            user = me.getUser();        me.fireEvent(‘save‘, me, values, user);        me.down(‘#hobbyTpl‘).update({            Name: user.get(‘Name‘),            FavoriteHobby: values.FavoriteHobby        });    },    // ...});

This small change can make the controller simple enough that it only needs to know the presence of the view and trigger a save event.

App/controller/hobby.js

Ext.define(‘Example.controller.Hobby‘, {    ‘Ext.app.Controller‘,    function () {        this.control({            ‘hobbyview‘: {                this.onSave            }        });    },    function (view, values, user) {        user.set(values);        user.save();    }});

Now, the controller does not need to understand the structure of the view at last. The controller only saves the data, but he only displays the data.

As long as the view keeps triggering save time, there is no need to modify the controller much now.

Controller knows

    • The view has a button that Itemid to save
    • button is a sub-component of the form
    • How to get values from a view's form
    • The form has a itemid for hobbytpl, how do I update it?
    • The form does not know the concept of user
Smart views are focused and easy to maintain and test

Knowing how to dismantle a mammoth controller can be quite helpful for a better team management class. Not only the controller, but also the view becomes more centralized and easy to maintain, they are also easy to test, and this is closer to the function of the Ext JS View Controller. Make the views smarter and easy for applications to reuse them.

To know is:

    • Views are fully capable of managing their own data
    • The controller should not understand the internal structure of the view as a prerequisite
    • Custom events are the perfect way to handle the communication between views and controllers

John Krull

John is a software Engineer at Emortgage Logic. He has experience in web App development, Agile Software Dev, and ui/ux design. He sp*ecializes in Ext JS, JavaScript, PHP, Perl, MySQL, HTML, and CSS.

"Translation" builds a maintainable controller in the Ext JS application

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.