What steps can I take to ensure that a callback is added only once?

Here is a section of code that I am working with:

.factory('Auth', function($firebaseAuth) {
var ref = new Firebase('https://myfirebase.firebaseio.com');
return $firebaseAuth(ref);
})

and an accompanying controller:

.controller("LoginCtrl", function($scope, Auth, $timeout) {
function authDataCallback(authData) {
    $timeout(function() {
        console.log(Auth);
        $scope.user = authData;

        if (authData) {    
            console.log("Authentication successful.");
        }
    });
}

$scope.auth = Auth;
console.log("Adding a new callback in login");
$scope.auth.$onAuth(authDataCallback);
...

In my application, there is a possibility for the user to be redirected back to the login page and thus causing the LoginCtrl controller to be called again. The issue arises when the same callback keeps getting added every time the login page is revisited, leading to multiple executions of the callback code.

Is there a way to remove or cancel these callbacks when leaving/loading a controller?

Thank you!

Answer №1

Include a public boolean property in your Auth service to track the user's authentication state. Once the user is authenticated, set this property to true.

Before executing the callback function, check whether it is necessary based on the previous value of the authentication state.

if (!Auth.isUserAuthenticated) {
   $scope.auth.$onAuth(authDataCallback);
}

While there are ways to ensure a function runs only once using libraries like lodash, the core issue lies in the architecture of your controller. Controllers are not singletons and execute at least once during the digest cycle. To address this, move all main business logic to services and let controllers manage behavior by interacting with these services.

This approach ensures cleaner code organization and separation of concerns between services and controllers.

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

Managing login API tokens in Vue JS

I have implemented a custom Login component in my Vue project: var Login = Vue.extend({ template: '#auth', data: function () { return {username: '',password: '',errorMessage:''}; }, methods : ...

Is there a way to enclose an element with two other elements using JavaScript/jQuery

Is it possible to create a wrapping element for content located between two existing elements? Here's a code snippet to illustrate: <p> Some text some text <span class="foo">some more text</span> additional text. </p> <p> ...

AngularJS ui-rangeSlider when the handle is released

Below is the HTML code snippet: <div range-slider min="0" max="100" model-max="rangevalue.value" pin-handle="min" onHandleUp="x()"></div> I am trying to achieve the following: $scope.x=function(){ console.log($scope.rangevalue.value) } How ...

Setting up users with email and phone provider via Admin Firebase

Is it possible to create a user with both phone number and email as providers in Firebase? Currently, the provided code only includes the setup for the phone number as the sole provider. https://i.sstatic.net/D7w0O.png admin.auth().createUser({ uid: em ...

Creating interactive click and model expressions in AngularJS

Within my ng-repeat loop, I am trying to implement the following toggle functionality: <a href='#' ng-model="collapsed{{$index}}" ng-click="collapsed{{$index}}=!collapsed{{$index}}">{{item.type}}</a> <div ng-show="collapsed{{$in ...

Using React: implementing a spinner upon clicking a button and transitioning to a new screen when the animation finishes

I have noticed that there are existing answers on incorporating spinners during fetch requests completion. However, my query pertains to stopping the animation once it reaches completion after a timeout. Additionally, I am seeking advice on best practices ...

A guide to exporting a PDF in A4 size landscape mode with jspdf

As a novice in UI development, I am currently trying to export HTML content to PDF using the JSPDF library. However, I have encountered difficulties in generating the PDF in A4 size landscape mode. The HTML code includes data with charts (canvasjs/chartjs) ...

Ensure that the HTML input element only accepts positive values, including decimal numbers

I need to build an input field that only accepts positive numbers, including decimal values. Leading zeros are not allowed, and users should not be able to paste invalid values like -14.5 into the field. Here is my current implementation: <input type= ...

ng-repeat does not update model when using track by

I've been facing an issue with checklist-model while working with an array of check-boxes. The problem arises when I try to delete selected items within an ng-repeat loop. Everything works fine initially, but when I add track by $index along with ng-r ...

How to stop Mouseenter event from bubbling up in an unordered list of hyperlinks using Vue 3

I've experimented with various methods to prevent event bubbling on the mouseenter event, but I'm still encountering an issue. When I hover over a link, the event is triggered for all the links as if they were all being hovered over simultaneousl ...

Rendering and sending with Node.js simultaneously

Is there a way to render Jade and send additional code after the render without replacing the existing Jade code? Here is an example: var express = require('express'); var router = express.Router(); router.get('/user', function(req, r ...

When I hover over the content, the image displayed in the tooltip is causing a flickering effect

Dealing with Angular in this situation, my goal is to have an image or video displayed inside a tooltip when hovering over specific content. However, there seems to be a flickering effect before the image renders, making the transition less smooth compared ...

Navigating Assets within NodeJS Module

I'm facing a challenge with my NodeJS module that is designed to translate XML to HTML using an XSL file. The issue arises when I try to package the XSL file along with the rest of the module. Currently, the XSL file is located inside the source fold ...

Encountering an Uncaught ReferenceError in AngularJS & Jasmine/Karma: require not defined

Recently, I've been delving into the world of testing my angular app with Jasmine-Karma. As someone who is a complete novice when it comes to testing, consoles, and npm, I'd really appreciate a simple explanation (and maybe some guidance) on what ...

Build a row within an HTML table that is devoid of both an ID and a class

Creating an additional row in an HTML table is a common task, but it can become tricky when dealing with multiple forms and tables on one page. In my case, I have a form that contains only a table element, and I want to move some columns from the first row ...

Ensuring Proper Validation of Forms in JavaScript

Hey there, I'm currently working on my website and encountered an issue with my form. It seems to be submitting to the success page even when the inputs are empty. I've looked through similar questions but haven't found a solution that works ...

Enhance Your Javascript and jQuery Coding Efficiency

On the website I am currently working on, there are multiple images that enlarge when hovered over. Each item has a unique class to indicate which image should expand upon hovering. I am looking to simplify this process by creating a single function that c ...

Tips for querying a MongoDB collection based on a date field?

My date string is formatted like this: '2021-03-09' This is how my mongodb collection looks: { "_id": { "$oid": "633aede250625c10dddfd57b" }, "title": "test 1", "desc ...

How is it that connecting an event listener to a React child component can be done in a way that resembles simply passing a prop

class Board extends React.Component { constructor(props) { super(props); this.state = { squares: Array(9).fill(null), }; } handleClick(i) { // do things } render() { return ( <div ...

A label in nativescript not displaying a two-digit number

I've encountered a peculiar issue with my user interface. I have a barcode scanner on my phone that scans barcodes and stores them in an observable array (which is functioning correctly). I also have a label that displays the length of the array. When ...