Monday, January 20, 2014

Button Icon Option Shortcut

The button widget, allows you to set the primary icon, the secondary icon, or both. The primary icon shows up the left of the button text, and of the text isn't displayed, it's just the primary icon that's displayed. The secondary icon shows up to the right of the button text. In general, the primary icon is the common path. However, the button options API is expecting an object every time we want to change just the primary button. Let's see how we can optimize for the common case and provide a simplified icon API.

Here's one way to do it. Just provide a new icon option for the button widget. This is much more straightforward to use, especially if your application uses a lot of button icons, none of which are secondary. So instead of $( "button" ).button( { icons: { primary: "ui-icon-check" } } ), we can do $( "button" ).button( { icon: "ui-icon-check" } ).

This works by first extending the _create() method, then extending the _setOption() method. The _create() method is the constructor — so we need to check if the new icon option has been passed to the options object. If it has, we're just passing that value onto the icons option. In other words, we're providing a simple translation layer. Same goes for the _setOption() method. It just performs a translation in much of the same way as _create().

The code to create the button using this approach is much smaller. Setting the icon via the option() method is simplified too.