A deep dive into the coordination between AngularJS factories and controllers

Can someone please explain the code snippet below to me? I found it on this website:

http://www.html5rocks.com/en/tutorials/frameworks/angular-websockets

Snippet from Factory:

app.factory('socket', function ($rootScope) {
var socket = io.connect();
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {  
        var args = arguments;
        $rootScope.$apply(function () {
          callback.apply(socket, args);
        });
      });
    },
    emit: function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          if (callback) {
            callback.apply(socket, args);
          }
        });
      })
    }
  };

Snippet from Controller:

function AppCtrl($scope, socket) {

  // Socket listeners
  // ================

  socket.on('init', function (data) {
    $scope.name = data.name;
    $scope.users = data.users;
  });

  $scope.sendMessage = function () {
    socket.emit('send:message', {
      message: $scope.message
    });

    // add the message to our model locally
    $scope.messages.push({
      user: $scope.name,
      text: $scope.message
    });

    // clear message box
    $scope.message = '';
  };
}

My questions are:

  1. What happens after the controller triggers

    socket.on('init',function(data){.....});
    ? The factory's socket.on method takes two parameters - eventName and callback. What does this callback function do?

  2. Why is $rootScope.apply being used?

  3. Can you explain what callback.apply does?

Answer â„–1

1. When the controller triggers socket.on('init',function(data){.....});, what happens next in terms of control flow? In a factory, when socket.on is invoked with two parameters - eventName and callback function, what exactly does this callback do?

There is no complexity in invoking socket.on from the controller. It directly triggers the on method within the factory.

By understanding the above process, it becomes clear that the callback refers to the second parameter passed into the function. In this case, it is the function

function (data) {  $scope.name = data.name;  $scope.users = data.users; }

2. What is the purpose of using $rootScope.apply?

https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply

The use of $rootScope.apply ensures that any changes made within its function are detected during a digest cycle.

3. Can you explain what callback.apply means?

It refers to the apply method available for all JavaScript functions. In this context, it is utilized to execute the callback function with the socket as the 'this' parameter and the arguments from the event handler as input.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Referencing an object by using a variable containing its name

I need a way to reference an object using a variable with its name in it. I've figured out how to do this for properties and sub-properties: var req = {body: {jobID: 12}}; console.log(req.body.jobID); //12 var subProperty = "jobID"; cons ...

How can you refresh a functional component using a class method when the props are updated?

I've created a validator class for <input> elements with private variables error, showMessage, and methods validate and isOk. The goal is to be able to call the isOk function from anywhere. To achieve this, I designed a custom functional compone ...

I'm having trouble sending registration emails through my server. What could be causing this issue?

Currently, I am in the process of developing a registration system that automatically sends an email with the user's username and password once they have successfully registered. The registration process functions smoothly up until the point where the ...

Having trouble with the installation of [email protected] on Windows 10 x64?

I am currently in the process of setting up hiredis on my Windows 64-bit operating system as it is a requirement for the node-celery package. My system specifications are as follows: Node v7.9.0 npm v4.5.0 Visual Studio Community 2013 with Update 5 (en_ ...

`Heart-shaped loading bar in Reactjs`

Looking for help in creating a heart-shaped progress loader for a React project. I attempted using CSS but encountered issues with the progress not filling the entire heart design. Below is the code snippet I used. The progress should start from the bottom ...

Guide to creating JSDoc for a TouchEvent handler

Looking to improve my shorter-js codebase with JSDoc for TypeScript definitions, but hitting a roadblock. I've implemented the on() function using Element.addEventListener, working well so far. However, when passing a TouchEvent as a parameter for an ...

JavaScript slowness

Currently, I am developing a test page that consists of buttons triggering various scripts. One of the functionalities I am trying to implement is changing the background color every second for 5 seconds, cycling through a total of 5 different colors. Desp ...

Converting a string to JSON format with JavaScript

My string is structured in JSON format like this: "{""c1"": ""value1"", ""c2"": ""value2""}" After storing it in an SQLITE database, I use the following Javascript code to retrieve it back as JSON: var req= "SELECT json_column from my_table"; var re ...

Retrieving the data from an automatically filled field

Is there a way to retrieve the value of the #id_start_date field if it already has a date filled in? I attempted this approach: let startDate = $("#id_start_date").val(); $("span.start_date").text(startDate); I also tried wrapping it inside a .change() ...

Convert XML data into a structured table format

We have an XML file named "servers.xml" that needs to be parsed. This file is located on the same server where we want it to be parsed, in the same folder. <root> <list> <server> <server name="28 Disconnects La ...

Retrieve information and functions from one component in a separate component

I currently have two components: ContainerSidebar.vue <!-- Sidebar --> <div id="b-sidebar"> <div class="change-image"> <img :src="profile.avatar != null ? profile.avatar+'#&apo ...

Tips for obtaining the node configuration within an HTML document

I have set up a node configuration based on the specific environment. Click here to see the details. Here is an example of the default.json file: { "server": { "host": "localhost", "protocol": "http", "port": 9011 } } My goal is to retri ...

"Utilizing the ui-grid feature to dynamically apply cell filters

I am looking to utilize ui-grid to create a column with a dynamic cellFilter that can be updated on the fly, from 'number' to 'currency', for example. I attempted changing the parameter cellFilter within the column but it does not refle ...

"Utilize Ember Data to extract data using a specific serializer

I'm working with an object called "Residence" that consists of various details. I am trying to use the serializer "extractSingle" to establish its relationships when receiving data from the server, but I keep encountering the error message "Unable to ...

Is it possible to retrieve the createdAt timestamp without displaying the 'GMT+0000 (Coordinated Universal Time)'?

After conducting an extensive search, I have yet to find a satisfactory answer. My goal is to configure it without including the CUT time. {name: "Registered:", value: `${user.createdAt}`}, {name: "Joined:", value: `${message.guild.joinedAt}`} Presently, ...

Updating the Structure of Various Objects with an Object Model Schema

Hello there, Query: Can you provide guidance on constructing a function that does the following: Accepts an object as the first argument; Takes a schema model as the second argument; The second argument is an array of objects with different models than t ...

Utilize a script to cross-reference coordinates received from the client API with those stored in

Having trouble comparing coordinates between an event in my database and those provided by the user's client API (after approval). The user's coordinates are currently only being logged in the terminal: Here's what I have in guestValidate.j ...

The Angular user interface typeahead feature fails to automatically fill in the text box when an option is

Utilizing the Angular UI typeahead directive has been quite helpful for me. I am working with a list of individuals in the typeahead dropbox, where each person is represented as an object with details like LastName, FirstName, CustomerNumber, and more. Des ...

Sharing Data Across Multiple Windows in Angular 2 Using a Singleton List

My multiplayer game involves adding new players to a single game room lobby, which is essentially a list of current players. How can I update this list for all connected players when new ones join? I implemented a service and included it in the providers ...

Is it safe to use v-html exclusively for text content?

The Vue Documentation mentions the usage of v-html to render inner HTML content. While this is a simple and legal method, concerns about the safety of using it in web projects linger in my mind. If I restrict the use of v-html to rendering harmless tags li ...