josei josei - 1 year ago 88
Javascript Question

Binding component state conditionally

I intend to change the state of several fields in a form (hide) according to the value selected in a combobox.

This can be done using methods such as setVisible () or setHidden ().

It will be possible to achieve this goal using binding component state?



Answer Source

Yes. Using ViewModel formulas. Quoting from the documentation:

Many configs you will want to bind are boolean values, such as visible (or hidden), disabled, checked, and pressed. Bind templates support boolean negation "inline" in the template. Other forms of algebra are relegated to formulas (see below), but boolean inversion is common enough there is special provision for it.

Basically, you can using bindings to control the visible attribute, but the binding needs to be a boolean value. You can see that with your 'isAdmin' check. So what you need to do is create a formula on the ViewModel and bind to that.

Ext.define('My.ViewModel', {
  extend: '',
  formulas: {
    isAlabama: function(get) {
      return get('comboboxvalue') === 'AL';

To use this, you'll need to say that you're using this view model in your panel. Also... you see the comboboxvalue bit? Well, it looks like ComboBoxes don't publish their value attribute to the view model automatically - you need to do that explicitly, like so:

{ xtype: 'combobox',
  fieldLabel: 'Choose State',
  store: states,
  queryMode: 'local',
  displayField: 'name',
  valueField: 'abbr',
  bind: {
    value: '{comboboxvalue}'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download