jam-cloud/app/assets/javascripts/findSession.js

120 lines
3.8 KiB
JavaScript
Raw Normal View History

(function(context,$) {
"use strict";
context.JK = context.JK || {};
context.JK.FindSessionScreen = function(app) {
var logger = context.JK.logger;
2012-11-28 02:29:46 +00:00
var sessionLatency;
var sessions = {};
var selectors = {
TABLE_BODY: '#findSession-tableBody'
};
function loadSessions() {
$.ajax({
type: "GET",
2012-11-28 02:29:46 +00:00
url: "/api/sessions",
success: startSessionLatencyChecks
2012-11-28 02:29:46 +00:00
});
}
function startSessionLatencyChecks(response) {
sessionLatency.subscribe(app.clientId, latencyResponse);
$.each(response, function(index, session) {
sessions[session.id] = session;
sessionLatency.sessionPings(session);
});
}
function latencyResponse(sessionId) {
renderSession(sessionId);
}
/**
* Not used normally. Allows modular unit testing
* of the renderSession method without having to do
* as much heavy setup.
*/
function setSession(session) { sessions[session.id] = session; }
/**
* Render a single session line into the table.
* It will be inserted at the appropriate place according to the
* sortScore in sessionLatency.
*/
function renderSession(sessionId) {
var $tb = $(selectors.TABLE_BODY);
var rowTemplate = $('#template-findSession-row').html();
var session = sessions[sessionId];
var latencyInfo = sessionLatency.sessionInfo(sessionId);
var vals = {
id: session.id,
genres: session.genres.join (','),
sortScore: latencyInfo.sortScore,
participants: session.participants.length,
description: session.description || "(No description)"
};
var row = context.JK.fillTemplate(rowTemplate, vals);
var insertedEarly = false;
$.each($('tr', $tb), function(index, nextRow) {
var $nextRow = $(nextRow);
var rowSortScore = parseInt($nextRow.attr('data-sortScore'), 10);
if (vals.sortScore > rowSortScore) {
$nextRow.before(row);
insertedEarly = true;
return false; // break
}
});
if (!(insertedEarly)) {
return $tb.append(row);
}
}
function afterShow(data) {
var $tb = $(selectors.TABLE_BODY);
$tb.empty();
loadSessions();
}
function deleteSession(evt) {
var sessionId = $(evt.currentTarget).attr("action-id");
if (sessionId) {
$.ajax({
type: "DELETE",
url: "/api/sessions/" + sessionId
}).done(loadSessions);
}
}
function events() {
$('#findSession-tableBody').on("click", '[action="delete"]', deleteSession);
}
/**
* Initialize, providing an instance of the SessionLatency class.
*/
function initialize(_sessionLatency) {
if (_sessionLatency) {
sessionLatency = _sessionLatency;
2012-11-28 02:29:46 +00:00
} else {
logger.warn("No sessionLatency provided.");
2012-11-28 02:29:46 +00:00
}
var screenBindings = {
'afterShow': afterShow
};
app.bindScreen('findSession', screenBindings);
events();
}
this.initialize = initialize;
this.afterShow = afterShow;
this.renderSession = renderSession;
// Following exposed for easier testing.
this.setSession = setSession;
this.selectors = selectors;
};
})(window,jQuery);