I have a collection of PlaylistItem
objects. They are linked together such that each item knows the ID of its next/previous item. I am iterating over this collection of objects, starting at a known position and working with each object once. I'm not a big fan of how I do this, but I am not seeing an obvious way of rewriting it.
var firstItemId = activePlaylist.get('firstItemId');
var currentItem = activePlaylist.get('items').get(firstItemId);
// Build up the ul of li's representing each playlistItem.
do {
var listItem = $('<li/>', {
'data-itemid': currentItem.get('id'),
contextmenu: function (e) {
var clickedItemId = $(this).data('itemid');
var clickedItem = activePlaylist.get('items').get(clickedItemId);
contextMenu.initialize(clickedItem);
// +1 offset because if contextmenu appears directly under mouse, hover css will be removed from element.
contextMenu.show(e.pageY, e.pageX + 1);
// Prevent default context menu display.
return false;
}
}).appendTo(playlistItemList);
$('<img>', {
'class': 'playlistItemVideoImage',
src: 'http://img.youtube.com/vi/' + currentItem.get('video').get('id') + '/default.jpg',
}).appendTo(listItem);
$('<a/>', {
text: currentItem.get('title')
}).appendTo(listItem);
currentItem = activePlaylist.get('items').get(currentItem.get('nextItemId'));
} while (currentItem && currentItem.get('id') !== firstItemId)
How would you write this?
Note that it is a do-while
because I want to ensure I always render that firstItem
. If there's only one item in the list, the loop will immediately terminate. Thus the need for the do-while
.