WebOS List Formatters

Here at Cardinal Peak, we’ve been doing quite a bit of development on webOS, Palm’s new operating system for smartphones. WebOS is based on Linux, and it relies heavily on web standards like HTML, CSS, and JavaScript. It’s a great programming environment, but since it’s also rather new, there’s a lot of tribal knowledge still to be built up around how to optimally develop for it. So this is the first of an occasional series where we will look at issues that arise when developing webOS applications.

A list formatter is a very powerful feature of webOS. Basically a formatter is a function that is applied to a property name, and it formats each list element for display to the user. Although it’s a great feature, I did not find it to be documented very well. Here’s a quick tutorial on how to use list formatters.

Let’s start in the HTML. In your scene, add a Mojo element for a List. The following line creates a simple list named ExampleList:

Let’s also create a row template for our list and save the file to our views folder (views/ExampleList/rowTemplate.html):

#{-myData}

The #(-myData} object is what we are going to replace in the HTML. The HTML could have been much more complex and the object itself could have been embedded in the middle of the HTML. This object just represents the portion of the HTML code which will be replaced by the formatter code.

In the JavaScript you reference your formatter as part of the attributes to the setupWidget call.

listAttributes = {
itemTemplate: 'example-list/rowTemplate',
formatters:{myData: this.setMyData.bind(this)}
};
this.controller.setupWidget('ExampleList', listAttributes, this.model);

The only required element of the listAttributes is the itemTemplate. For our example we are adding the optional formatters and to the myData key we are instructing it to call the setMyData function. The key name that you use here must match the property name in the HTML.

The last piece to the puzzle is the formatter function itself:

setMyData: function(propertyValue, model) {
if(model.isHappy) {
model.myData = "Feeling Happy";
}
else {
model.myData = "Feeling Sad";
}
}

Now, when the myData field in the model is modified, the HTML will replace the #{-myData} property name with one of the strings “Feeling Happy” or “Feeling Sad.” In this case the HTML string was simple text to display. The string could have also been any properly validated HTML string.

model.myData = '< img src="images/happy.jpg" />';

This combination of list templates and list formatters should allow you to come up with both complex and dynamic lists in webOS.

Find code for this here.