我的index.ejs
文件上有一个表,该表应该显示当前登录的用户(通过附加表行)。以下是它的构建方式:
<table id="status-table" class="table table-bordered table-hover">
<thead>
<tr>
<th>Player</th>
<th>Status</th>
<th>Score</th>
</tr>
</thead>
<tbody></tbody>
</table>
在我的user.js
模型(文件路径:assets / js / user.js)中,我创建了这个函数:
addUser: function(user) {
var found = false;
// Check if the user is already in the table
$('#status-table tr').each(function() {
var hasUser = $(this).attr('id');
if (hasUser !== undefined && ('user-' + user.id == hasUser)) {
found = true;
}
});
if (!found) {
var $table = $('#status-table');
var ready = (user.id == me.id) ? '<button type="button" id="changeStatus" class="btn btn-default btn-xs">change</button>' : '';
var row = '<tr id="user-'+user.id+'"><td class="name" data-avatar="'+user.avatar+'">'+user.name+'</td><td><img class="flag" src="http://api.hostip.info/flag.php?ip='+user.ip+'" width="20" height="14" alt=""><span class="status" data-status="'+user.status+'">'+user.status+'</span>'+ready+'</td><td class="score">'+user.score+'</td></tr>';
$table.append(row);
QW_MODULES.chat.updateUI();
}
}
此函数应该触发,因为在我的app.js
中,我在“套接字连接”上调用整个user.js
文件的初始化。
io.socket.on('connect', function socketConnected() {
QW_MODULES.user.init();
});
不解雇此功能会出现什么问题?我在登录/注册时没有收到任何错误。
编辑:这是我的用户函数init'd:
var QW_MODULES = (function (modules, $) {
"use strict";
var self;
var user = {
init: function() {
self = this;
},
// Add a user to the list of available users to play with
addUser: function(user) {
var found = false;
// Check if the user is already in the table
$('#status-table tr').each(function() {
var hasUser = $(this).attr('id');
if (hasUser !== undefined && ('user-' + user.id == hasUser)) {
found = true;
}
});
if (!found) {
var $table = $('#status-table');
var ready = (user.id == me.id) ? '<button type="button" id="changeStatus" class="btn btn-default btn-xs">change</button>' : '';
var row = '<tr id="user-'+user.id+'"><td class="name" data-avatar="'+user.avatar+'">'+user.name+'</td><td><img class="flag" src="http://api.hostip.info/flag.php?ip='+user.ip+'" width="20" height="14" alt=""><span class="status" data-status="'+user.status+'">'+user.status+'</span>'+ready+'</td><td class="score">'+user.score+'</td></tr>';
$table.append(row);
QW_MODULES.chat.updateUI();
}
},
// Remove a user from the table of available users to play with, by sending
// either a user object or a user ID.
removeUser: function(user) {
// Get the user's ID.
var id = user.id || user;
var userName = $('#user-'+id).text();
// Remove the corresponding element from the users table
var userEl = $('#user-'+id).remove();
QW_MODULES.chat.updateUI();
},
// Add multiple users to the users list.
updateUserList: function(users) {
$('#status-table tbody tr').remove();
users.forEach(function(user) {
if ((typeof user.id === 'undefined') || (user.status === 'offline') || (typeof me === 'undefined')) {
return;
}
self.addUser(user);
});
}
};