Skip to content

Instantly share code, notes, and snippets.

@elcuervo
Created January 3, 2012 22:28
Show Gist options
  • Save elcuervo/1557287 to your computer and use it in GitHub Desktop.
Save elcuervo/1557287 to your computer and use it in GitHub Desktop.
var Picomachine = require('picomachine');
var WebSocket = require('websocket-client').WebSocket;
var WebRocket = function(key, options) {
this.key = key;
this.options = options || {};
this.connection = new WebRocket.Connection;
};
WebRocket.prototype = {
connect: function() {},
disconnect: function() {},
};
WebRocket.Socket = WebSocket;
WebRocket.Connection = function(url) {
var initialState = 'disconnected';
var self = this;
this.url = url;
this.machine = new Picomachine(initialState);
this.state = initialState;
this.on = this.machine.on;
this.machine.transitionsFor['connect'] = {disconnected: 'connecting'};
this.machine.transitionsFor['connected'] = {connecting: 'connected'};
this.machine.transitionsFor['forbid'] = {connecting: 'forbidden', connected: 'forbidden'};
this.machine.transitionsFor['unavailable'] = {connecting: 'unavailable', connected: 'unavailable'};
this.machine.transitionsFor['disconnect'] = {connect: 'disconnected', connecting: 'disconnected'};
this.machine.on('any', function() { self.state = this.state; });
this.machine.on('connected', function() {
console.log('connected');
});
this.machine.on('connecting', function() {
var machine = this;
this.socket = new WebRocket.Socket(self.url);
this.socket.onopen = function() {
machine.trigger('connected');
};
this.socket.onerror = function() {
machine.trigger("unavailable");
}
});
};
WebRocket.Connection.prototype = {
connect: function() {
this.machine.trigger('connect');
}
};
WebRocket.Channel = function() {};
module.exports = WebRocket;
@elcuervo
Copy link
Author

elcuervo commented Jan 4, 2012 via email

@oboxodo
Copy link

oboxodo commented Jan 4, 2012

I like state machines.

I don't know about JS performance problems. But if that code works, I would just use it until its performance proves to be a problem. Just THEN I would change it for something else.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment