Last active
August 29, 2015 14:18
-
-
Save wachpwnski/f27f44ee6bf01ffe513d 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
'use strict'; | |
/* Singleton AutobahnJS Websocket Connection as AngularJS Service */ | |
angular.module('AutobahnJSWebsocketService', []) | |
.factory('Websocket', ['$q', function($q) { | |
var openSession = null; | |
var isOpening = false; | |
var waitingList = []; | |
return { | |
// get the session from the open websocket | |
session: function () { | |
var deferred = $q.defer(); | |
if (isOpening) { | |
// while the connecton is opening another process might ask for a session | |
// to prevent multiple connections, we add his promise to a waitinglist, | |
// it gets resolved as soon as the current opening connection is established | |
waitingList.push(deferred); | |
} else if (openSession) { | |
deferred.resolve(openSession); | |
} else { | |
isOpening = true; | |
var connection = new autobahn.Connection({url: 'ws://127.0.0.1:8080/ws', realm: 'gerater'}); | |
connection.onopen = function (session, details) { | |
console.log("Connection open"); | |
openSession = session; | |
isOpening = false; | |
deferred.resolve(openSession); | |
// resolve all promises in waitinglist | |
angular.forEach(waitingList, function (deferred) { | |
deferred.resolve(openSession); | |
}); | |
}; | |
connection.onclose = function (reason, details) { | |
console.log("Connection lost: " + reason); | |
} | |
connection.open(); | |
} | |
return deferred.promise; | |
} | |
} | |
}]); | |
/* Controller using the service */ | |
angular.module('ExampleController', []) | |
.controller('ExampleCtrl', ['$scope', '$q', 'Websocket', function($scope, $q, Websocket) { | |
Websocket.session().then(function (session) { | |
var deferred = $q.defer(); | |
session.call('my.procedure').then( | |
function (res) { | |
deferred.resolve(res); | |
}, | |
function (err) { | |
deferred.reject(err); | |
} | |
); | |
}); | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment