Created
January 3, 2012 22:28
-
-
Save elcuervo/1557287 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.