Issue with event handling when using the `this` keyword in function

What is causing the this keyword to return undefined in the event handler and how can this issue be resolved?

twittyApp.factory('Unshown', function () {
function Unshown() {
    this.allIsLoaded = false;
    this.loading = false;
    this.firstTime = true;
    this.scrollMarker = 100;
    this.loadedUnshownPages = 0;
    this.timeLineHiader = $cookies.get("lastReadedTweetId");
}
window.onscroll = function () {
     //Why is 'this.scrollMarker' undefined here?
};
return Unshown;
});

Answer №1

Implement the following changes

twittyApp.factory('Unshown', function() {

    var fact = {};

    function Unshown() {
        this.allIsLoaded = false;
        this.loading = false;
        this.firstTime = true;
        this.scrollMarker = 100;
        this.loadedUnshownPages = 0;
        this.timeLineHiader = $cookies.get("lastReadedTweetId");
    }

    var objUnShown = new Unshown();
    window.onscroll = function() {
        objUnShown.scrollMarker // access scroll marker
    };

fact.Unshown = objUnShown;

    return fact.Unshown;
});

You need to create an object of Unshown class in order to access its properties.

EDIT 2 : if you want to create an object whenever needed, follow this approach.

twittyApp.factory('Unshown', function() {

        var fact = {};

        function Unshown() {
             ..
        }

        window.onscroll = function() {
            objUnShown.scrollMarker // access scroll marker
        };

    fact.Unshown = Unshown;


        return fact;
    });

 /// Within the controller, instantiate the object like this.

 var objUnshown = new Unshown.Unshown()

Answer №2

When you utilize the this keyword within the functions of Unshown, you are defining properties for that function object. To retrieve those properties outside of the function, make use of the property accessor on the reference to the function object.

twittyApp.factory('Unshown', function () {
function Unshown() {
    this.allIsLoaded = false;
    this.loading = false;
    this.firstTime = true;
    this.scrollMarker = 100;
    this.loadedUnshownPages = 0;
    this.timeLineHiader = $cookies.get("lastReadedTweetId");
}
window.onscroll = function () {
     //this.scrollMarker is undefined
     //
     //Use property accessor
     console.log(Unshown.scrollMarker);
};
return Unshown;
});

Implementing window.onscroll in AngularJS

The utilization of window.onscroll represents the older method of registering event listeners.

In the context of AngularJS, event listeners can be added using Angular's jqLite.

var windowElem = angular.element($window);

windowElem.on('scroll', function scrollListener (event) {
    console.log(event);
};

Ensure that you include $window in the list of injectables for the factory function.

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

Is it possible to swap out images using srcset attribute?

Currently, I am facing an issue regarding changing the img on mobile and tablet devices to display different images. As a beginner with jQuery, I couldn't resolve it using that framework, so I am exploring options with html5. I am wondering if there ...

Using material community icons in conjunction with react-native-vector-icons

I am facing an issue with displaying the store-front icon from the Material Community Icons library in my React Native app. Here is the code snippet causing the problem: import { StatusBar } from "expo-status-bar"; import React from "react&q ...

Is there a way to simulate the Bun global object using Jest?

Currently, my tech stack includes Bun, Typescript (TS), and Jest. As I work on writing my tests, I encounter the need to mock Bun.file functionality. Here is a snippet from my tsconfig.json: { "compilerOptions": { "lib": ["ESNext"], " ...

I crafted this dropdown menu, but for some reason, the selections aren't registering when clicked. Below is the code I used. Any assistance would be greatly appreciated!

Hi there, I need some help with getting my code to run properly. I've created a dropdown box using HTML and CSS, but it seems like there's an issue with the JavaScript portion as the options are not being selected. I've included a code snipp ...

"Implementing Vue mousemove functionality only when the mouse button is pressed

Is it possible to initiate a mouse movement only after the element has been clicked first? I am exploring this functionality for an audio player timeline. .player__time--bar(@mousedown="setNewCurrentPosition($event)") .slider(role="slider" aria-valuem ...

Adjusting the minimum value on a textfield with JQuery Validate plugin in real-time

I am attempting to dynamically update the minimum value on one field based on input from other fields. Here is a brief overview of my code: $("#new_project").on("click", function() { switch($('input:radio[name=quality-level]:checked').val() ...

The performance of the Ajax Jquery remove function leaves something to be desired

My table has items with a delete button for each row. To achieve this, I created the following Ajax function: $(document).ready(function() { $(".destroy-device").click(function(e) { e.preventDefault(); var id = $(this).attr("data-id"); $.aj ...

Fetching the URL for the Facebook profile picture

Utilizing satellizer for authentication in a MEAN application. Once the authentication process is complete, I aim to retrieve the user's profile picture. Below is the code snippet that I am using: Angular Controller (function(){ 'use strict ...

React - Issues with setTimeout() method not triggering following Promise.all execution

I am facing an issue with my arrow function that is called from the `componentDidMount` lifecycle method to fetch updated status of schedules every 20 seconds using a `setTimeout()`. The problem is that the `setTimeout()` method does not trigger another re ...

Issues arise when attempting to manipulate the DOM with ng-view in AngularJS

Apologies for not providing the code due to its length. I have a simple application with a single module, controller, and ng-view/routProvider. In my controller, when I use console.log(angular.element('div').length), it correctly shows that ther ...

Update the message displayed in the user interface after the view has been fully rendered in an Express application, following the execution of asynchronous

I have created a simple express app that reads files from a directory, renames them, zips the files asynchronously, and then renders another view. The file reading and renaming are done synchronously, while the zipping part is handled asynchronously. My cu ...

The steps to implement an onchange function for displaying image previews in a profile image tag

Within my code, there is a profile image tag along with an input tag for updating the image. I aim to implement a functionality that allows me to select a new image and automatically update the profile picture when it changes <div class="col-sm-6"> ...

There was an issue retrieving the value from the $.ajax() error function, as it returned [

After successfully receiving data from the input field and sending it to the database, everything seems to be working fine. However, when attempting to retrieve the data after sending it to the database, an error is encountered: [object HTMLInputElement]. ...

The Javafx WebEngine's executescript() function is unable to send a multiline string

Issue: I'm struggling to make the JavaFX WebEngine trigger a JavaScript function when using a Java String object with multiple lines. If I input the following example in HTML: "asd" ENTER "qwe" into the textArea, and then click the send button, the f ...

Retrieve childNodes of the Select All input using jQuery from the container node with the class name "container"

I am trying to retrieve the text value of all the childNodes within the container of the corresponding input when the Select All checkbox is checked. Currently, my code captures the text inside each input label. However, it only logs the label (e.g. &apos ...

What is the best way to pass a JSON object containing an array of objects to a Spring controller?

Currently, I have set up two domain models in Hibernate using @OneToMany mapping. My goal is to generate a JSON object on the frontend and then transmit it to the Spring MVC controller so that the model data can be automatically set. The main model classe ...

Display jqgrid with borders and insert extra headers text at the top of the grid

function generateTableWithText(){ $("#active_grid").jqGrid("exportToHtml",{ includeLabels : true, includeGroupHeader : true, includeFooter: true, autoPrint : true ...

Is NextJS Route Handler in Version 13 Really Secure?

Within my forthcoming NextJS 13 web application, I am in the process of integrating an API through route handlers to facilitate functions like user registration and login procedures. Is it considered safe when transmitting sensitive data like a user's ...

What is the best way to handle errors in the front-end when receiving responses from expressjs?

Here is the issue that I am facing: //express server app.post('/register', (req, res) => { const { password, passwordConfirm } = req.body; if (password === passwordConfirm) { //... } else { ...

The invocation of Firebase ref.once() seems to have inexplicably gone unnoticed

I've been working on an alarm app with Firebase integration. The goal is to add 3 sample tasks to the list when a user first uses the app, and save them to Firebase. However, I'm facing an issue where these sample tasks keep getting added every t ...