12

I am adding some websocket functional to our angular app. The Websocket object is wrapped in a service. Ideally we would like our wrapped socket object to have a standard event API so that we can use it in the controller like the following: (Sorry for the Coffeescript)

angular.module('myApp').controller 'myCtrl', ($scope, socket) ->
  update = (msg)->
    $scope.apply ->
      #do something regarding to the msg

  socket.on 'message', update

  unregister: ->
    socket.off 'message', update  

What's the best practice/library for us to achieve this? Use jquery? Backbone.Events? Any suggestion will be helpful. Thanks!

KailuoWang
  • 1,304
  • 1
  • 12
  • 24

1 Answers1

19

You don't need to use any library to achieve this, just create a service, inject $rootscope and publish the events from there to rootscope, then in your controller listen for that event.

var socket; // this be the socketio instance.
angular.module("myApp").factory("SocketHandler", function ($rootScope) {
  var handler = function (msg) {
    $rootScope.$apply(function () {
      $rootScope.$broadcast("socketMessageReceived", msg);
    });
  };

  socket.on("message", handler);

  $rootScope.$on("unregisterSocket", function () {
    socket.off("message", handler);
  });
}).controller("myCtrl", function ($scope, SocketHandler) {
  var listener;
  var addListener = function () {
    listener = $scope.$on("messageReceived", function (e, msg) {
      console.log("New Message: " + msg);
    }); // $on returns a registration function for the listener
  };
  var removeListener = function () {
    if (listener) listener();
  };
});
Umur Kontacı
  • 35,403
  • 8
  • 73
  • 96
  • Thank you for the answer fastreload, however this is not exactly what I need. In my example, the controller has the ability to unsubscribe to socket message for itself only, in another sentence, the subscription is on the granularity of controllers - each controller can decide when to subscribe and when to unsubscribe. Thoughts? – KailuoWang Mar 16 '13 at 16:57
  • Thanks fastreload. That's not a bad solution. – KailuoWang Mar 18 '13 at 19:42