Mobile App Tutorial: Backbone Models Database with Titanium Alloy

Since the Alloy plug-in release, Titanium development has been extremely simple and fast. In this tutorial I will show you how to implement a local database with backbone models in 5 simple steps.

Backbone using titanium alloy

Considerations before starting this tutorial:

1) Have installed the latest version of Titanium Studio.

2) Have a basic knowledge of how to use Titanium/Alloy MVC framework.

NOTE: This tutorial has been created using an OSX environment and Titanium 3.1.1 SDK version.


Step 1

Go ahead and create a new mobile app project (“Default Alloy Project”) called it ToDoList.


Step 2

Let’s create a new model in the "models" folder inside "app" folder; let’s call it toDoList.js

1.- Right click on the Models folder > Create Alloy Model

<span style="font-family: 'courier new', monospace;">exports.definition = {</span>
<span style="font-family: 'courier new', monospace;">    config : {</span>
<span style="font-family: 'courier new', monospace;">        columns : {</span>
<span style="font-family: 'courier new', monospace;">            "id_toDoList": "INTEGER PRIMARY KEY AUTOINCREMENT",</span>
<span style="font-family: 'courier new', monospace;">            "value" : "TEXT",</span>
<span style="font-family: 'courier new', monospace;">            "hasCheck": "BOOLEAN"</span>
<span style="font-family: 'courier new', monospace;">        },</span>
<span style="font-family: 'courier new', monospace;">        adapter : {</span>
<span style="font-family: 'courier new', monospace;">            type : "sql",</span>
<span style="font-family: 'courier new', monospace;">            collection_name : "toDoList",</span>
<span style="font-family: 'courier new', monospace;">            idAttribute: "id_toDoList",</span>
<span style="font-family: 'courier new', monospace;">        }</span>
<span style="font-family: 'courier new', monospace;">    }</span>
<span style="font-family: 'courier new', monospace;">}</span>


Step 3

The next step is creating the UI, go to the index.xml file and insert this code:

      <em>&lt;!-- Instance of the model --&gt;</em>
      &lt;Collection src="toDoList" /&gt;
      &lt;Window class="container"&gt;
            &lt;TextField id="tfInsert"&gt;&lt;/TextField&gt;
            &lt;Button id="btnInsert" &gt;Insert&lt;/Button&gt;
            <em>&lt;!-- Specifies the collection singleton or instance to bind to the table. --&gt;</em>
            &lt;TableView id="tbToDoList" dataCollection="toDoList"&gt;
                  <em>&lt;!-- rowId="{id_toDoList} is a custom property in order to have a reference to the primary key of the records --&gt;</em>
                  &lt;TableViewRow id="listRow" rowId="{id_toDoList}" hasCheck="{hasCheck}"&gt;
                        &lt;View id="componentView"&gt;
                             <em>&lt;!-- text="{value} is the value of the record of the database --&gt;</em>
                        &lt;Label id="lblValue" text="{value}"&gt;&lt;/Label&gt;


Step 4

Go to the index.css and insert this code:

".container": {
      hasCheck: false
      font: {
            fontFamily: "HelveticaNeue",
            fontSize: "12sp"


Step 5

Here’s the fun part the index.js file:

<em>//Opens the window</em>


      <em>//Hides the keyboard in iOS</em>
      <em>//if there is something in the textbox</em>
      if($.tfInsert.value != ""){
            <em>//This is how we are creating an instance of a model</em>
            var listModel = Alloy.createModel("toDoList", {
                  <em>//with out custom parameters</em>
                  value: $.tfInsert.value,
            <em>//This is how we save a model to our databaseif the model already exists, the save will be an "update".</em>
            <em>//Resets the model's state from the database</em>
            alert("Please fill out the text field above.");


      <em>//Factory method for instantiating a Backbone collection of model objects</em>
      var recoverDatabase = Alloy.createCollection("toDoList");
      <em>//We need the database to iterate through it</em>
      recoverDatabase.fetch({query:"SELECT * FROM toDoList"});


      for(var i=0; i&lt;recoverDatabase.length;i++){
            <em>//This is how we are getting the value of id:toDoList .at(i).get("id_toDoList")</em>
            if("id_toDoList") == e.row.rowId){
                  var table = Alloy.createCollection("toDoList");
                  <em>//e.row.rowId is a custom property created in the .xml file that contains the primary key of every value in the database</em>
                  table.fetch({query:"SELECT * FROM toDoList where id_toDoList = " + e.row.rowId });
                  <em>//if the query returned with more than 0 rows</em>
                if(table.length &gt; 0){
                  <em>//if the record(hasCheck) of the column is false</em>
                      if("hasCheck") == false){
                             e.row.hasCheck = true;
                             <em>//This is how we set a value to the database</em>
                                   <em>//then we set it to true</em>
                             <em>//if not we set it to false</em>
                             e.row.hasCheck = false;
                        <em>//Get the latest database state</em>


<em>//if we do a longpress we can delete the row</em>
      var tableViewEvent = e.row;
      var alertDialog = Titanium.UI.createAlertDialog({
          title: 'Remove',
          message: 'Do you want to remove this row?',
          buttonNames: ['Yes','No'],
          cancel: 1


      alertDialog.addEventListener('click', function(e) {


          if (e.index == 0) { <em>// clicked "YES"</em>
          } else if (e.index == 1) { <em>// clicked "NO"</em>


function removeRow (_row) {
      var recoverDatabase = Alloy.createCollection("toDoList");


      recoverDatabase.fetch({query:"SELECT * FROM toDoList"});


      for(var i=0; i&lt;recoverDatabase.length;i++){
            if("id_toDoList") == _row.rowId){
                  var table = Alloy.createCollection("toDoList");
                  table.fetch({query:"SELECT * FROM toDoList where id_toDoList = " + _row.rowId });
                if(table.length &gt; 0){
                  <em>//To remove a row from the database we use destroy()</em>


<em>//Resets the model's state from the database useful if you'd like to ensure that you have the latest database state.</em>

So this is what you will see in your mobile app project:

Local database using alloyDatabase alert using alloy

Also, you can pull all the code to your existing mobile app project, with github. Just click here!


Final thoughts

This is a really quick example of mobile app development on how to integrate backbone models with titanium in alloy. Hope this little tutorial helped you in your coding. If you have any questions, let us know.  Feel free to share this software development tutorial with your friends. All of us at iTexico will continue bringing you more software and mobile app development tutorials, share best practices, and other industry news as part of our blog series.


About the author

Mario Galván is an iTexico Software Engineer and Mobile Developer with ~2 years of experience with Titanium development for mobile application development. He currently works as a Software Engineer at iTexico developing multiple mobile app projects for clients.

Download our Free E-Book and learn how the Product Mindset can benefit your mobile app. 

Through this guide, we want to give you, product owners, product managers, engineers, entrepreneurs and anybody looking to build great digital products, more insights into the importance of user-centric design and development and how to correctly achieve it.

How Product Mindset Can Save your Sinking App

You may also like:

Post Your Comment Here