fill me (list) up scotty

Posted: January 28, 2013 in javascript, snippets

The mission: create a jquery api to easily add an item(li) to a list (ul) in the html domain in a certain predefined format.

This was pretty easy but is useful.

// JavaScript Document

/////////////////////////////////////////////////////////////////////////////
// CLASS ListLiLoader
/////////////////////////////////////////////////////////////////////////////

function ListLoader(_ulId, _liTemplate, _replacePhrases)
{
/*VARIABLES*/
var ulId = _ulId;
var liTemplate = _liTemplate;
var replacePhrases = _replacePhrases;

/*FUNCTIONS*/
this.addItem = function (values)
{
var finalLiDom = liTemplate;

if (values.length > replacePhrases.length)
{
// can’t do this task….
return;
}

for (var i=0; i < values.length; i++) {
finalLiDom = finalLiDom.replace(replacePhrases[i], values[i]);
}

$(“#”+ulId).append(finalLiDom);
$(“#”+ulId).listview(‘refresh’);
}

}

how to use?

initialize an instance of the ListLoader object:

var gAllWorkoutsListLoader = new ListLoader (
allWorkoutsList“,
“<li>#VALUE#</li>”,
[“#VALUE#”]
);

the first arg is the html id of the list:

<ul data-role=”listview” data-inset=”true” id=”allWorkoutsList” style=”margin-bottom:0px”>
</ul>

the second argument is the pattern. put in some text that u want to replace when inserting a new LI.

for example, I will want to replace the entire content of the LI with some plain text.

the third argument is an array with the phrases to look for when replacing values in the template (arg2)

now call the addItem method with an array that contains values to replace according to the third argument of the constructor.

workoutsTable.getWorkouts(
function (res)
{
//alert (“result=”+res.length);
for (var i=0; i<res.length; i++){
//alert (“res”+i+”= ” + res.item(i).date + “,” + res.item(i).duration);
var date = new Date(res.item(i).date * 1000);
var d = date.getDate();
var day = (d < 10) ? ‘0’ + d : d;
var m = date.getMonth() + 1;
var month = (m < 10) ? ‘0’ + m : m;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;

gAllWorkoutsListLoader.addItem([month + “/” + day + “/” + year + ” Duration:” + res.item(i).duration] );
}
}
);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s