Dynamically creating jQuery Mobile radio buttons with Mustache
Filed under: jQuery Mobile
comments (6) Views: 19,755
This afternoon I had a reader email me with a question about dynamically creating radio buttons in a jQuery Mobile app after load and getting them to render. He was using my previous blog post on refreshing jQuery Mobile components but couldn't get the radio buttons to work. So I whipped up a quick demo to make sure it was possible. Turns out it is, but there's a trick.
The first thing I did was to write it up procedurally using jQuery object creation. It works, but its long and ugly; plus there was duplication. Here's what I came up with first:
Yep, it's ugly all right...pretty verbose too. But it's all there. Check the demo and you'll see that "the hard way" runs just fine and allows you to pick your favorite seasoning. But I knew there was a better way to accomplish this task. So I reached for the Mustache templating language. You might recall that we've looked at Mustache before. Performing this same task with Mustache was much simpler, easier to read, and didn't duplicate code, which is a great thing. Let's look at the code after refactoring to use Mustache:
In this case I'm defining the template as a string of HTML right inline. You probably wouldn't do this in production but taking this route helps me avoid an AJAX call. I'm also hard-coding the data being passed into the template renderer, which in a real app you'd more than likely be looping over a data set. Run the demo though and you'll see that the easy way results in tasty snacks for everyone.
Here's the part that was likely throwing off our reader. You'd think that after defining the radiogroup object through hard-coding or templating, you could immediately render it using .trigger('create') or .checkboxradio('refresh') but you'd be wrong. Using the former merely runs without actually converting the plain HTML to jQuery Mobile elements, and the latter actually throws an error.
Uncaught cannot call methods on checkboxradio prior to initialization; attempted to call method 'refresh'
It appears that when dynamically creating elements and inserting them in this manner you have to first insert them into their resting place, then render their container using .trigger('create') as in the second example above.
Hope this helps someone else.
If this article was interesting, or helpful, or even wrong, please consider leaving a comment, or buying something from my wishlist. It's appreciated!