Creating a Five Star component in Umajin

Part 1 – Five Star Component

This is a fully working ‘Five Star’ display for data binding – and input control for raising events. The user can adjust the graphics for the on and off stars. When clicked on, the component will raise the on_up event passing the value back to be used in actions with the normal square brackets syntax (e.g. [value]).

Here is all of the javascript along with two graphics to use for the star_images in
Scroll down to part 2 of the tutorial to see the version which supports half stars

There are three main sections in the code below. Lets go through them in order.

1) RegisterComponent and Init. This sets up the properties for our component which is the ability to change the value and the graphics for the star’s on and off state. The init function explicitly creates the star images and positions them inside the component each taking 20% of the horizontal space each. We also listen for the ‘on_up’ event so this can be used as an input control as well as display.

2) Then we have the ‘on_up’ event which takes the users input from mouse, touch, pen or gesture and works out what to do. We take this position multiply it by the five stars and divide it by the overall width of the component to work out which star they clicked on. We also store this back into the value for the properties of this component and raise the event should users want to add actions when people rate something.

3) Finally we have the ‘drawing’ function which updates the stars based on an incoming value when databinding, or from a users click. This looks up the images we have to use and the current value from the data store. It then assigns the right star picture to the five images we created in step 1.

That’s literally all there is to this really cool and functional component.

Part 2 – Five Star HALF Component

OK, lets look at a new control which is able to handle half stars. e.g. 0.0 stars, 0.5 stars, 1.0 stars, 1.5 stars, 2.0 stars, 2.5 stars, 3.0 stars, 3.5 stars, 4.0 stars, 4.5 stars, 5.0 stars.

Here is a zip with the javascript and graphics for this five star half component

The primary change is to allow real numbers (fractions) not whole numbers (integers). A new graphic, the starhalf graphic. We also used a loop in the new version of section three to reduce the amount of code. This now has to check three possible states, no star, half a star or a whole star. So we loop over each of the 5 stars rather than write that out in full!