Tabris.js Selector API
Tabris provides a powerful API for selecting any widget or collection of widgets in the UI tree.
Ids, classes, immediate child selectors
For those familiar with css – we can use id, classes and relationship selectors such as > in much the same way. Set an id on your widget
1 |
Button id='submit' |
… and select away:
1 |
page.find('#submit') |
Constructor class
We can also select elements by widget type using the constructor class name:
1 |
page.find(Composite) |
This would select all instances of Composite
widgets, including those that are subclasses of Composite, for example, Tab
or CollectionView
.
WidgetCollection
Whenever a selector is used, it creates a WidgetCollection
. A WidgetCollection
is array-like. We can access elements within the collection by index. The WidgetCollection
API is a subset of the widget
API. Methods we can call on a collection include set
, append
, animate
.
1 2 3 |
collection .set({background: 'blue'}) .animate({opacity: 0}, {duration: 400}) |
Here we simultaneously set the background of all widgets in the collection blue and animate them to 0 opacity i.e invisible over a duration of 400ms. Neat.
.only()
We can use the methods first()
and last()
on a WidgetCollection
to access the first and last elements of a collection. If we pass a selector as a parameter to these methods they will return the first/ last element that matches that selector.
only()
behaves like first()
in that it returns the first element in a collection. However it also checks that this element is the only
element in the collection and if not, it throws an exception. This is useful where only one element is expected to match a selector.
.apply()
We can call this method on a Composite
(a widget that can contain other widgets) and any of its subclasses. The apply method allows us to simultaneously select widgets and set their properties.
1 2 3 4 |
page.apply({ '#okbutton': {text: 'OK!', background: 'yellow'}, '#cancelbutton': {text: 'Cancel!', textColor: 'red'} }); |
If we wanted to select and set the properties of the page itself we can use the :host
pseudo selector that refers to the widget that applies the selector.
1 2 3 |
page.apply({ ':host': {background: 'yellow'}, }); |
This blog post has only scraped the surface of the selector API. For a full rundown of ways of selecting widgets in the UI see the Tabris documentation.
Feedback is welcome!
Want to join the discussion?Feel free to contribute!