peerlink/example/static/chat.js
2014-08-28 14:52:31 +02:00

90 lines
2.9 KiB
JavaScript

var names = {};
Ox.load(function() {
var app = window.app = {};
app.triggerEvent = function(action, data) {
if (action == 'info') {
Ox.$('#id').html(data.id);
Ox.$('#nick').val(data.nick || '');
var peers = Ox.$('#peers');
peers.empty()
data.local.forEach(function(peer) {
console.log('add', peer);
if (names[peer]) {
Ox.$('<div>')
.html(peer + '(' + names[peer] +')')
.appendTo(peers);
} else {
app.getNick(peer, function(nick) {
var html = peer;
if(nick) {
html = peer + '(' + nick +')';
}
Ox.$('<div>')
.html(html)
.appendTo(peers);
});
}
});
} else if (action == 'message') {
var html = (names[data.from] || data.from) + ': ' + data.message;
Ox.$('<div>').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);
}
});
});