Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best practice to do event driven development in Angular.js apps?

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!

like image 213
KailuoWang Avatar asked Mar 16 '13 01:03

KailuoWang


People also ask

What is event-driven architecture and when should I use it?

Event-driven architectures are ideal for improving agility and moving quickly. They're commonly found in modern applications that use microservices, or any application that has decoupled components. When adopting an event-driven architecture, you may need to rethink the way you view your application design.

How events are used in AngularJS?

An Events in AngularJS can be used to perform particular tasks, based on the action taken. Both Angular Event & the HTML Event will be executed & will not overwrite with an HTML Event. It can be added using the Directives mentioned below: ng-mousemove: The movement of the mouse leads to the execution of the event.

Is angular event driven programming?

Angular is based on Event Driven or Data Driven Model. using of ngRx follows which pattern data driven or event driven.


1 Answers

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();
  };
});
like image 173
Umur Kontacı Avatar answered Oct 21 '22 16:10

Umur Kontacı