Rene Rubalcava | December 14, 2014
Recently I have been toying around with a library called xstyle that is maintained by the same guys that maintain the Dojo Toolkit. At first glance, it may seem like another css preprocessor, similar to Sass or less, which are both great tools. However, once you dive in, it can do so much more.
Keeping it dynamic
If you've read my blog before, you know I'm a big fan of using Dojo to keep my code modular, even using dynamic loading. The first thing I had tried with xstyle was loading my css files dynamically. You can find some details here. But you can basically load the css only when needed when a module is loaded, like this.
This is great for working with modules that may or may not be used in your application. In my case however, this is a little less important to me because I use less and my build process will typically handle this, but that's not to say it doesn't come in handy. The aspect of xstyle that really got me excited was building UI components from css templates. Now that sounded like fun.
How xstyle nearly broke me
Next I have a widget that doesn't really do much other than load the css and sets up a module used as the model for the component.
Now, let's look at what the css looks like.
Here is a look at the model that does all the work.
By using model = module('widgets/mywidget/model'); in the css, you now have access to methods on the model. This is just a plain object with methods. You can't really initialize a constructor the way you do with dijit widgets. This is why I used this widget to pass some parameters, including the map to the model. If you look at the css, you can see that we can bind a method of the model to the keyup event by using on-keyup: model/updateValue(event). Then the button can bind the click event to another method by using on-click: model/find(). This find method fires off a FindTask and will zoom to a location. The search is configured for state names, so search for Texas or California.
This is just a quick rundown, you can find the whole project on github.
Components rule, Dijits drool
Ok, slow down. xstyle is still fairly new and it's not going to replace Dijits in Dojo 2.0, but is a very interesting way of building components. I'm thinking this might be a great way to build tiny widgets, something similar to the LocateButton or HomeButton. I'm still experimenting with it myself. I for one use simple buttons to activate more complex widgets all the time, so this could be a great way to build small reusable components in my applications.
I highly encourage you to give it a shot and experiment. If anything you may find just dynamically loading your css files with the accompanying widget to be well worth the effort.