landers.angular
Version:
landers.angular
83 lines (82 loc) • 3.64 kB
JavaScript
;angular.module('Landers.angular')
.provider('LaravelEcho', function() {
var provider = this,
global_echo,
channels = {};
provider.enabled = true;
provider.publicChannel = 'BroadcastDefaultChannel';
// provider.presenceChannelPrefix = 'presence-';
provider.presenceChannel = 'BroadcastMemberChannel';
provider.privateChannelPrefix = 'private-member.';
provider.initGlobal = function(options){
if (provider.enabled) {
var opts = angular.extend({
broadcaster: 'socket.io',
secure: false,
host: '',
namespace: '',
}, options || {});
for (var k in opts) {
if (opts[k] === undefined) delete opts[k];
}
global_echo = new Echo(opts);
}
};
this.$get = ['$timeout', function($timeout){
return {
provider: provider,
getGlobaEcho: function(){
return global_echo;
},
joinPrivate: function(channel){
return global_echo ? global_echo.private(channel) : null;
},
joinPublic: function(channel){
return global_echo ? global_echo.channel(channel) : null;
},
registerChannel: function(scope, channel, callback){
// 用$timeout, 允许在不同模块中监听同一channel
$timeout(function(){
if (!channels[channel]) {
callback();
channels[channel] = true;
if (scope) {
scope.$on('$destroy', function() {
channels[channel] = false;
global_echo.leave(channel);
});
}
} else {
callback();
}
}, 200);
},
registerChannelEvent: function(scope, Channel, events){
this.registerChannel(scope, Channel.name, function(){
for (var event in events) {
(function(event){
Channel.listen(event, function(e){
events[event].call(global_echo, e);
});
})(event);
}
});
},
listenPrivate: function(scope, auth_id, events){
var Channel = this.joinPrivate(provider.privateChannelPrefix + auth_id);
Channel && this.registerChannelEvent(scope, Channel, events);
},
// listenPresence: function(scope, events) {
// var Channel = this.joinPublic(provider.presenceChannelPrefix + provider.presenceChannel);
// this.registerChannelEvent(scope, Channel, events);
// },
listenPublic: function(scope, events){
var Channel = this.joinPublic(provider.publicChannel);
Channel && this.registerChannelEvent(scope, Channel, events);
},
leave: function(channel) {
global_echo.leave(channel);
}
};
}];
});