A binding agreement

Some of the state of the application is held in the URL, but other transient state is held in view models. We're going to look at an example of how data flows through this application in order to better understand how powerful data binding can be.

In portrait mode, our application has a menu button that toggles the visibility of various other components. The pseudocode for this could be:

if menu_button_is_pressed
   this.find('searchfield').show()
   this.find('newmessagebutton').hide()
   this.find('logo').hide()
else 
   this.find('searchfield').hide()
   this.find('newmessagebutton').show()
   this.find('logo').show()
end

Code like this isn't complicated, but it's lengthy and error prone, a chore to write. Instead, we can use data binding to avoid this type of code and set up the behavior during configuration, something like this:

[
    {
   	      xtype: 'button', reference: 'menubutton',
   	      enableToggle: true
   	},
    {
         xtype: 'searchfield', 
         bind: { 
               hidden: '{menubutton.pressed}'
         }
    }
]

There are a couple of things to understand here: firstly that a button will "publish" the state of its pressed value. Whenever pressed changes, either programmatically or because the user clicked on the button, the value will be pushed to the view model for this button. Secondly, if a component has its reference set, this will be available to access its published values in the view model.

Combine both of these and the bind configuration on the search field becomes clear; bind the value of hidden on the search field to the value of pressed on the menu button. If pressed is true, the search field will be hidden.

While we've covered data binding and view models in some detail in previous chapters, this is the first time we've looked at this particular approach. It's not even necessary to specify any configuration on the view model itself as long as one is available somewhere in the component hierarchy, this will work.

This is another weapon in the armory of tools that allow us to simplify our code. Using this kind of declarative approach, where we specify what we'd like to happen, but don't have to say how it happens, we can avoid writing methods like the pseudocode earlier and use a standardized approach that Ext JS provides.

The tricky part is fully embracing data binding and the view model concept. By thinking up-front about the dependencies between components and channeling data through view models, powerful interactions can be created with very little code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset