Note:
- I am very new to Javascript.
- The code I provided is long but not complicated.
The code below works and runs fine. But I would like to seperate it out into logical 'pure' functions to make it clearer whats going on. I started to re-factor this myself and made some good progress, however, I quickly started to return to problems with dependencies and embedded functions.
I'd be interested to see how others would write the following:
var contactsController = {
fetch: function()
{
// Parses the returned JSON into the database
var fetchSuccess = function(json)
{
var NAME = "Contact",
COLUMNS = ['Name', 'GivenNames', 'FamilyName', 'Telephone'];
if (json.Response.Code == 0)
{
database.open();
database.dropTable(NAME);
database.createTable(NAME, COLUMNS);
// .Contact is an array of contact objects
var contacts = json.Contacts.Contact;
for (var contact in contacts)
{
var contact = contacts[contact];
database.insert(NAME, COLUMNS, [ontact.Name, contact.GivenNames, contact.FamilyName, contact.Telephone] );
}
contactsController.populateList();
}
}
ServerConn.fetchContacts(fetchSuccess);
},
populateList: function()
{
var $page = $("#contactsPage");
$page.find(".content").empty();
$page.find(".content").html("<ul data-role='listview' data-filter='true'><\/ul>");
$list = $page.find(".content ul");
var render = function(character)
{
return function(tx, result)
{
var max = result.rows.length;
if (max > 0)
{
var header = "<li data-role='list-divider'>" + character + "</li>",
listItem = $(header);
$list.append(header);
for (var i = 0; i < result.rows.length; i++)
{
var contact = result.rows.item(i),
strHtml = "<li><a href='#contactPage'>" + contact.Name + "<\/a><\/li>";
listItem = $(strHtml);
$list.append(listItem);
// store the data in the DOM
$list.find("a:last").data("contactObj", contact);
}
$list.find("a").click(function()
{
var $this = $(this);
$("#contactPage").data("contactObj", $this.data("contactObj"));
});
$list.listview(); //Only fires once?
$list.listview('refresh');
}
}
}
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(var i = 0; i < str.length; i++)
{
var sql = "SELECT * FROM Contact WHERE Exclude = ? AND Name LIKE ? ORDER BY Name",
nextChar = str.charAt(i),
selargs = ['0', nextChar + "%"];
database.open();
database.query(sql, selargs, render(nextChar));
}
}
};