Skip to content

Commit

Permalink
refactor api.js
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangtao committed Mar 27, 2019
1 parent f44b563 commit b4aac98
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 15 deletions.
2 changes: 1 addition & 1 deletion backend/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ func (s *Backend) handler(w http.ResponseWriter, r *http.Request) {
s.tran.Transfer(log)
}
//persist
s.pers.Add(fmt.Sprintf("[%s]", name), log+"\n")
go s.pers.Add(fmt.Sprintf("[%s]", name), log+"\n")

//send to web
go s.api.SendLog(name, log)
Expand Down
40 changes: 26 additions & 14 deletions public/scripts/api.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
var socketio = io(document.location.href + 'socket.io/')
var socketio = null;
var dispatch = {
logger: null,
}
socketio.on('connect', function() {
socketio.on('log:log', log => {
if (dispatch.logger) {
dispatch.logger(log);
}
});
});

socketio.on('disconnect', function () {
});

var SubscribeToLog = function(tag, cb) {
socketio.emit('log:subscribe', tag);
dispatch.logger = cb;
if (socketio === null) {
socketio = io(document.location.href + 'socket.io/');
socketio.on('connect', function() {

});
socketio.on('log:log', log => {
if (dispatch.logger) {
dispatch.logger(log);
}
});
socketio.on('disconnect', function () {
socketio.close();
socketio = null;
});
socketio.emit('log:subscribe', tag);
dispatch.logger = cb;
} else {
socketio.emit('log:subscribe', tag);
dispatch.logger = cb;
}

}
var SocketClose = function() {
socketio.close();
socketio = null;
}
3 changes: 3 additions & 0 deletions public/scripts/log.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ var LogBox = React.createClass({
componentDidMount: function() {
SubscribeToLog(this.state.tag, this.logHandler);
},
componentWillUnMount: function() {
SocketClose();
},
render: function() {
return (
<div className="logbox">
Expand Down

0 comments on commit b4aac98

Please sign in to comment.