[ExtJS5 Study Notes] section 10 ViewModel and DataBinding, extjs5viewmodel for new features of Extjs5

Source: Internet
Author: User

[ExtJS5 Study Notes] section 10 ViewModel and DataBinding, extjs5viewmodel for new features of Extjs5

Address: http://blog.csdn.net/sushengmiyan/article/details/38612721

Author: sushengmiyan

--------------------------------------------------------------- Resource link -----------------------------------------------------------------------

Http://docs.sencha.com/extjs/5.0/application_architecture/view_models_data_binding.html

API Docs: http://docs.sencha.com/extjs/5.0/apidocs! /Api/Ext. app. ViewModel

Certificate ------------------------------------------------------------------------------------------------------------------------------------------------

Component binding

DataBinding and ViewModel are new powerful features of Ext JS5. They allow you to write the least code and use the declarative style to help you decouple management.

A ViewModel is a class that manages data objects. It allows components that are interested in data to be bound to it and will be automatically notified when changes occur. A ViewModel is referenced by a View like a ViewController. Because the ViewModel has a relationship with the view, in the component inheritance relationship, the view model self-ray owned by the ancestor can also be connected. This allows subclass to easily inherit the parent class.

The component has a bind configuration attribute that allows you to associate any configuration data from the ViewModel. With bind, you can be sure that the setter method configured by the component will be automatically bound when the value changes, and you do not need to write the event for processing.

In this guide, we can use several examples to learn about the powerful functions of ViewModels and DataBinding.


Perhaps the best way to understand Binding and ViewModels is to look at the different Binding methods you use on the components. This is because components are the original users of data binding and are well known by Ext JS developers. To enable binding, we need to first create a ViewModel so that we can introduce it later.

Binding and Configs)

Binding data to a component is a process of connecting Ext. app. ViewModel to the Configuration Attribute of the component. Any component configuration can be bound as long as there is a setter method. For example, if there is a setTitle method in the Ext. app. panerl. Panel class, you can bind the title configuration.

In the following example, we configure the panel Data Based on ViewModel. We can describe that our data is bound to width because of the setWidth method.

Ext. create ('ext. panel. panel ', {title: 'simple Form', viewModel: {type: 'test' // define the ViewModel test later}, bind: {html: '<p> Hello {name} </p>', width: '{someWidth }'}});

The syntax used to bind data is similar to Ext. Template. You can place Jiang text in curly brackets or format fomatters. Unlike Ext. Template, when only one image '{someWidth} is input, it is not converted into a string.

We will see later how name and somewidth are defined. 'The above example shows how data is used by components.

Bind a boolean data configuration

For example, visibility isvisible, availability disable, selected status checked, and button press status pressed need to be configured with a Boolean attribute. See the following example:

Ext.create('Ext.panel.Panel', {    title: 'Simple Form',    viewModel: {        type: 'test'    },    items: [{        xtype: 'button',        bind: {            hidden: '{!name}'  // negated        }    }]});

When the button is pressed, the value is passed into the setHidden method. Therefore, when a single value is passed in, it is not interpreted as a string, which is one reason.

Binding and priority

Binding configuration properties will overwrite the previously defined static values, but there may be a little delay.

Ext.create('Ext.panel.Panel', {    title: 'Simple Form',    viewModel: {        type: 'test'    },    bind: {        title: 'Hello {name}'    }});
Once the name binding is defined, the title of 'simple form' will be replaced.

Bind and subcontrol

One of the most useful parts of binding is the data in the container, which can be obtained by sub-components. The following example shows that the child component of viewmodel is bound with the data of the parent container.

Ext.create('Ext.panel.Panel', {    title: 'Simple Form',    viewModel: {        type: 'test'    },    layout: 'form',    defaultType: 'textfield',    items: [{        fieldLabel: 'First Name',        bind: '{firstName}' // uses "test" ViewModel from parent    },{        fieldLabel: 'Last Name',        bind: '{lastName}'    }]});

Two binding methods

Data can be bound in two ways. Data modified on the view can be immediately returned to the model. All components bound to this data will be updated.

In the above example, because the 'firstname' and 'lastname' attribute stones are bound to text, changes in the input box will be promptly notified to the following ViewModel. in order to see how to connect them, it is necessary to add examples.


Ext.define('TestViewModel', {    extend: 'Ext.app.ViewModel',    alias: 'viewmodel.test', // connects to viewModel/type below    data: {        firstName: 'John',        lastName: 'Doe'    },    formulas: {        // We'll explain formulas in more detail soon.        name: function (get) {            var fn = get('firstName'), ln = get('lastName');            return (fn && ln) ? (fn + ' ' + ln) : (fn || ln || '');        }    }});Ext.define('TestView', {    extend: 'Ext.panel.Panel',    layout: 'form',    // Always use this form when defining a view class. This    // allows the creator of the component to pass data without    // erasing the ViewModel type that we want.    viewModel: {        type: 'test'  // references alias "viewmodel.test"    },    bind: {        title: 'Hello {name}'    },    defaultType: 'textfield',    items: [{        fieldLabel: 'First Name',        bind: '{firstName}'    },{        fieldLabel: 'Last Name',        bind: '{lastName}'    },{        xtype: 'button',        text: 'Submit',        bind: {            hidden: '{!name}'        }    }]});Ext.onReady(function () {    Ext.create('TestView', {        renderTo: Ext.getBody(),        width: 400    });});

When the Panel is displayed, we can see that the changes in the input box are reflected to the panel title, and we can also see the status of the submit button.


Bind component Status

Sometimes, the status of a component, such as the checked in the selection box or the selected status of a table, is a concern of other components. When a component is set to reference for recognition, this component is popularized in ViewModel.

In the following example, we have an admin key input box. The status is determined by the selected status of the Selection box. This kind of behavior is suitable for dynamic forms:

Ext.create('Ext.panel.Panel', {    title: 'Sign Up Form',    viewModel: {        type: 'test'    },    items: [{        xtype: 'checkbox',        boxLabel: 'Is Admin',        reference: 'isAdmin'    },{        xtype: 'textfield',        fieldLabel: 'Admin Key',        bind: {            disabled: '{!isAdmin.checked}'        }    }]});

Binding description

So far, we can see three basic table binding descriptions:

{FirstName}: This is directly transmitted from the view model. It is not modified and can be of any type.

Hello {name}: characters can be inserted.

{! IsAdmin. checked} can have a negative sign, that is, a negative sign.

In addition to the above three methods, there are other less useful methods.

Multiple bindings
Ext.create('Ext.Component', {    bind: {        data: {            fname: '{firstName}',            lname: '{lastName}'        }    }});
Firstname and lastname are bound.

Bind record

For example, you can find the user record bound with id = 42.

Ext.create('Ext.Component', {    bind: {        data: {            reference: 'User',            id: 42        }    }});

This requires Ext. data. Session.

Associate binding

View the user's adress attributes

Ext.create('Ext.Component', {    bind: {        data: {            reference: 'User',            id: 42,            association: 'address'        }    }});

In this example, it is similar to binding the above record.

Binding operation

The following example shows how to destroy a single binding. Single operation used

Ext.create('Ext.Component', {    bind: {        data: {            bindTo: '{name}',            single: true        }    }});

Use the deep operation to bind the update of the reference operation

Ext.create('Ext.Component', {    bind: {        data: {            bindTo: '{someObject}',            deep: true        }    }});

Creating a ViewModels view model has learned how to bind it. Now it is time to learn about ViewModel and its functions.

As previously stated, ViewModel is an object for managing underlying data.

Rule Formulas

In order to bind data, the view model provides a convenient way to calculate data through formulas, which allows you to focus only on the life structure in the view without worrying about data dependencies.

In other words, the Formulas data can display different values without modification.

Ext.define('TestViewModel2', {    extend: 'Ext.app.ViewModel',    alias: 'viewmodel.test2',    formulas: {        x2y: function (get) {            return get('x2') * get('y');        },        x2: function (get) {            return get('x') * 2;        }    }});

Explicitly bound Formulas

In the preceding example, the correlation of the formula is found to pass the function check. However, this is not always the best solution. You can use an explicit binding declaration, which returns a simple object when all values are bound.

Ext.define('TestViewModel2', {    extend: 'Ext.app.ViewModel',    alias: 'viewmodel.test2',    formulas: {        something: {            bind: {                x: '{foo.bar.x}',                y: '{bar.foo.thing.zip.y}'            },            get: function (data) {                return data.x + data.y;            }        }    }});





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.