Browse files

split listen to setupSync and listen

  • Loading branch information...
1 parent c76f4ba commit 62ec2e57f86c04c9fe0d75638a3280109036c11f @mkuklis mkuklis committed Apr 1, 2013
Showing with 18 additions and 11 deletions.
  1. +18 −11 lib/index.js
View
29 lib/index.js
@@ -19,12 +19,19 @@ exports.listen = function(server, backends, options) {
// Serve client-side code
io.static.add('/backbone.io.js', { file: __dirname + '/browser.js' });
-
+ setupSync(io, backends, options);
+
+ return io;
+};
+
+var setupSync = exports.setupSync = function(io, backends, options) {
+ options || (options = {});
+
// Listen for backend syncs
Object.keys(backends).forEach(function(backend) {
io.of(backend).on('connection', function(socket) {
var sync = new Sync(backend, socket, options);
-
+
socket.on('listen', function(channel, callback) {
if (channel) {
socket.set('channel', channel, function() {
@@ -35,11 +42,11 @@ exports.listen = function(server, backends, options) {
callback(options);
}
});
-
+
socket.on('sync', function(req, callback) {
socket.get('channel', function(err, channel) {
req.channel = channel;
-
+
sync.handle(backends[backend], req, function(err, result) {
callback(err, result);
@@ -55,25 +62,25 @@ exports.listen = function(server, backends, options) {
});
});
});
-
+
// Proxy events on the backend to the socket
var events = { 'created': 'create', 'updated': 'update', 'deleted': 'delete' };
Object.keys(events).forEach(function(event) {
var listener = function(model) {
socket.emit('synced', events[event], model);
};
-
+
backends[backend].on(event, listener);
-
+
socket.on('disconnect', function() {
backends[backend].removeListener(event, listener);
});
});
- });
+ });
});
-
+
return io;
-};
+}
exports.middleware = {};
@@ -82,4 +89,4 @@ fs.readdirSync(path.dirname(__dirname) + '/middleware').forEach(function(filenam
exports.middleware.__defineGetter__(name, function() {
return require('../middleware/' + name);
});
-});
+});

0 comments on commit 62ec2e5

Please sign in to comment.