With Alloy and Hyperloop, you can quickly and easily expose native UI as Custom Alloy tags by leveraging the namespace (ns) attribute and commonjs modules.
Alloy allows you to create your own UI element that can be included into the XML View heirarchy in one of two ways, an Alloy Widget or through the use of Custom Tags.
To create your own custom tag, you link the tag to the commonjs module with the namespace attribute (ns). Here is an example using a custom tag to render a standard Titanium View:
<!-- index.xml -->
<Alloy>
<Window class="container" >
<!-- Standard Titanium View with a red backgroundColor-->
<View id="viewContainer" backgroundColor="red">
<!--
Custom Tag, leverages a commonjs module to create the view based on its name.
Any attributes on the tag are passed into the associated funciton as an object
-->
<Square module="square" color="blue" size="100" />
<!-- ^ ^
| |------- local attribute, will be passed in as part of the object passed to the commonjs function
|
|----- This is the namespace attribute, it links this tag to a commonjs module file in app/lib/square.js
-->
</View>
</Window>
</Alloy>
For the tag to actually render, you need to have a function that corresponds to the tag within the XML View
// app/lib/square.js
/**
* Square creation function - creates a small square view
* @params options {Object} - xml tag attributes passed in as a singular object
*/
exports.createSquare = function(options) {
// Create a new Ti View
var square = Ti.UI.createView();
// Update View based on XML attributes
square.backgroundColor = options.color || "black";
square.height = options.size || 50;
square.width = options.size || 50;
// Return the View, this will be added automatically by Alloy to the parent view element
return square;
};
In the commonjs module above, its important to note that we're export a function called createSquare
. This is necessary since the Alloy Custom Tag (Square) is going to look for that particular naming convention.
If your tag name was <BarChart ns="charts" />
then you would use the following notation in your commonjs module located at app/lib/charts.js
:
exports.createBarChart = function(options){
};
The namespace reference is a way to point the custom tag to the appropriate commonjs module. This can be nested under multiple folders or can just be a file under the app/lib
folder of your Alloy app.
Note: If you are referencing the file from within the
lib
folder, you do not have to specifically call outlib
in the namespace reference. Child folders under thelib
folder would need to be included in the namespace (Ex.<BarChart ns="charts/barchart" />
would be correct if you had a fileapp/lib/charts/barchart.js
).