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

117 lines
3.7 KiB
JavaScript

(function(context,$) {
context.JK = context.JK || {};
context.JK.FindSessionScreen = function(app) {
var logger = context.JK.logger;
var sessionLatency;
var sessions = {};
var selectors = {
TABLE_BODY: '#findSession-tableBody'
};
function loadSessions() {
$.ajax({
type: "GET",
url: "/api/sessions",
success: startSessionLatencyChecks
});
}
function startSessionLatencyChecks(response) {
sessionLatency.subscribe(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) {
$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 = JK.fillTemplate(rowTemplate, vals);
var insertedEarly = false;
$.each($('tr', $tb), function() {
$this = $(this);
var rowSortScore = parseInt($this.attr('data-sortScore'), 10);
if (vals.sortScore > rowSortScore) {
$this.before(row);
insertedEarly = true;
}
});
if (!(insertedEarly)) {
return $tb.append(row);
}
}
function afterShow(data) {
$tb = $(selectors.TABLE_BODY);
$tb.empty();
loadSessions();
}
function deleteSession(evt) {
var sessionId = $(this).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;
} else {
logger.warn("No sessionLatency provided.");
}
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);