Skip to content

ViewController Live Selectors

Brian Kotek edited this page Aug 20, 2013 · 9 revisions

[Back to Additional Features] (Additional-Features)

Deft JS 0.8 also introduced live selectors for view objects specified in the control configuration of a ViewController. In essence, this creates a dynamic control element.

As we saw in the earlier section on accessing views, a ViewController can specify a control block such as:

control: {
  manufacturingFilter: {
    change: "onFilterChange"
  }
},

This sets up a reference to a view item with an id or itemId of manufacturingFilter, and attaches an event listener for the change event. However, this reference and event listener are set up when the ViewController is created. If the manufacturingFilter were added or removed from the view after creation, the reference and listener would not be created or removed. This is where live selectors come in.

Here is the same configuration using a live selector:

control: {
  manufacturingFilter: {
    live: true,
    listeners: {
      change: "onFilterChange"
    }
  }
};

This means that the ViewController will watch for items being added or removed from the view. If a child with the id/itemId of manufacturingFilter is added to the view, the reference in the ViewController will be updated and the listener created. If manufacturingFilter is removed from the view, the reference is nulled out and the listener removed.

As you can imagine, this is extremely useful in a ViewController that manages a view with dynamically added or removed child items. Keep in mind that this does add some overhead, since Deft JS has to monitor the view continuously. So you don't want to just make all of your control items use live selectors. However, in cases where you need to handle things being dynamically added or removed, it's a very powerful feature.

Live selectors support any or all of the following structures:

control: {

  // Reference only, with no listeners
  nameTextField: {
    live: true
  },
  
  // Reference and listener
  addressTextField: {
    live: true,
    listeners: {
      change: "onAddressChange"
    }
  },
  
  // Reference and listener with listener options
  cityTextField: {
    live: true,
    listeners: {
      change: {
        fn: "onCityChange",
        single: true,
        scope: this
      }
    }
  },
  
  // Reference by selector and multiple listeners
  stateComboBox: {
    live: true,
    selector: "fieldcontainer > combobox"
    listeners: {
      boxready: "onStateBoxReady",
      select: "onStateSelected"
    }
  }
};  

Next: Promises API