')
.html(peer + '(' + names[peer] +')')
.appendTo(peers);
} else {
app.getNick(peer, function(nick) {
var html = peer;
if(nick) {
html = peer + '(' + nick +')';
}
Ox.$('
')
.html(html)
.appendTo(peers);
});
}
});
} else if (action == 'message') {
var html = (names[data.from] || data.from) + ': ' + data.message;
Ox.$('
').html(html).appendTo(Ox.$('#messages'));
}
Ox.print(action, data);
};
app.socket = new WebSocket('ws://' + document.location.host + '/ws');
app.socket.onopen = function(event) {
app.triggerEvent('open', event);
};
app.socket.onmessage = function(event) {
var data = JSON.parse(event.data);
app.triggerEvent(data[0], data[1]);
};
app.socket.onerror = function(event) {
app.triggerEvent('error', event);
app.socket.close();
};
app.socket.onclose = function(event) {
app.triggerEvent('close', event);
setTimeout(connectSocket, 1000);
};
app.request = function(action, data, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
try {
var response = JSON.parse(this.response);
callback && callback(response);
} catch(e) {
Ox.print('FAIL', this.response);
}
}
xhr.open('POST', '/' + action);
data = JSON.stringify(data);
xhr.send(data);
};
app.api = function(action, data) {
console.log('api', action, data);
app.socket.send(JSON.stringify([action, data]));
};
Ox.$('#send').on({
click: function() {
var value = Ox.$('#message').val();
if (value) {
app.api('sendMessage', {
message: value
});
}
}
})
app.getNick = function(peer, callback) {
app.request('info', {id: peer}, function(response) {
names[peer] = response.nick;
callback(response.nick);
});
}
Ox.$('#nick').on({
change: function() {
app.api('nick', this.value);
}
});
});