Data binding in Ext JS 5
Data binding is a beaten-to-death concept in UI frameworks. You bind the value of a variable to some property of an UI component. Any changes to the value of the variable will result in changes to the UI component and vice versa. Ext JS 5 introduces this concept using a new class called ViewModel. The ViewModel manages the binding between the data and the view components.
Let’s create a simple example to use the ViewModel. We’ll bind password textbox with a ViewModel. Based on the length of the password field we would like to display a tick mark or a cross mark. The tick or cross marks indicate the strength of the password. Figure 1.0 shows the password text box which is empty initially. So you have a cross mark displayed. As you start typing the password and the length of the value reaches five a tick mark appears as shown in Figure 2.0.
Figure 1.0: Password textfield with a cross mark by the side
Figure 2.0: Password textfield with a tick mark by the side
Let’s define our ViewModel class with the password data and a simple formula to calculate the length of the password.
Ext.define('SignUpViewModel', { extend: 'Ext.app.ViewModel', alias: 'viewmodel.signup', data: { password:"", }, formulas : { passwordlength : function(get){ return get("password").length > 5; } } });
The SignUpViewModel class contains the password field and passwordlength function that returns a boolean based on the length. We’ll bind the SignUpViewModel with our password textbox like this.
Ext.create('Ext.panel.Panel', { layout : "hbox", title : "Data binding", viewModel: "signup", items : [ { xtype : "textfield", inputType : "password", emptyText : "Password", bind : { value : "{password}" } }, { xtype : "image", src : "http://www.clker.com/cliparts/e/3/9/7/1245686792938124914raemi_Check_mark.svg.hi.png", height:"80%",width:"2%", bind : { hidden : "{!passwordlength}" } }, { xtype : "image", src : "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_DEG40dmCdNXtY5HRmgaoCbNz1eAgAovSG3uCBYBKSUO_H64S", height:"80%",width:"2%", bind : { hidden : "{passwordlength}" } } ] });
As you can notice in the code, the viewmodel property is mapped to the signup ViewModel. The bind property is used to map the value of the textfield with the password data field. The passwordlength formula is bound with the image components.
Though ViewModel is a useful feature, the documentation that talks about the internals of the ViewModel says it’s pretty memory intensive and needs to be used judiciously. With the introduction of this ViewModel Ext JS 5 applications can be built using MVVM(Model-View-ViewModel) architecture as well. So we have now two architectural options to build applications, MVC and MVVM.