The `this` property in XmlHttpRequest's onload event

In the given code snippet above, the variable this inside the _onChunkComplete method refers to the XHR request by default. However, is there a way to modify this so that it represents the actual Uploader object instead?


           function Uploader(file, options) {    
            // ... code here ....
            this.upload_request = new XMLHttpRequest();
            this.upload_request.onload =  this._onChunkComplete;
          }

          Uploader.prototype = {
            // ... code here ...
            _onChunkComplete: function() {
                if (this.range_end === this.file_size) {
                    console.log('done');
                    return;
                }
                this.range_start = this.range_end;
                this.range_end = this.range_start + this.chunk_size;
                if (!this.is_paused) {
                    this._upload();
                }
            }
             // ... more code here...
          };

          var test = new Uploader(formFile, {});
          test.start();
        

Answer №1

Implement the bind method:

this.upload_request.onload = this._onChunkComplete.bind(Uploader)

By using the bind() method, a new function is created with its context set to the specified value and additional arguments can be passed when calling the new function.

Answer №2

To utilize the Uploader object in the function, simply pass it as a parameter:

Uploader.prototype = {
    // ... code here ...

    var uploader = this;

    _onChunkComplete: function(uploader) {

        // you can now use the uploader object

        if (this.range_end === this.file_size) {
            console.log('done');
            return;
        }
        this.range_start = this.range_end;
        this.range_end = this.range_start + this.chunk_size;
        if (!this.is_paused) {
            this._upload();
        }
    }
    // ... more code here...
};

If you prefer to override this with the uploader object, refer to Martriay's answer.

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

Fixing the NodeJS error "TypeError: Crud.Select_products is not a function" is crucial for the proper functioning of your application

I am attempting to access a class that has been exported from the Crud.js file, but I am encountering an error. My objective is to run a sql query. Error: TypeError: Crud.Select_products is not a function at C:\xampp\htdocs\react\c ...

Getting the most out of your single react-select with Yup schema

I'm having issues with the validation of my form using react-select, Formik, and Yup. The schema I'm using is as follows: const Schema = Yup.object().shape({ age: Yup.object().shape({ label: Yup.string().required("Required"), value: Yup. ...

Identifying the issue of body.onload not being triggered

My web pages use body.onload (or window.onload) to properly set up, but sometimes the onload event is not being triggered. Is there a way in a specific web browser (preferably Chrome, where this issue seems more common) to identify what is causing the pag ...

React higher order component (HOC) DOM attributes are causing the error message 'Unknown event handler property' to be triggered

I recently created a Higher Order Component (HOC) using recompose, but I'm encountering a React Warning every time the props are passed down. Warning: Unknown event handler property `onSaveChanges`. It will be ignored. All my properties with a speci ...

An error occurred while trying to access the property 'send' which is undefined

I am currently facing an issue while attempting to send data to the router from an external script. The error message that I receive is TypeError: Cannot read property 'send' of undefined Below is the code snippet: app.js var Cake = require(&a ...

Javascript beginner attempting to grasp the DOM using AJAX, feeling perplexed (conceptual)

I'm a data guy who dabbles in Python and web development, but lacks understanding of JavaScript and the DOM. Recently, I encountered a strange issue that prompted me to seek clarity on the mechanics behind it. The problem scenario: There are numerou ...

Center the image within the div by setting its position to absolute

<div class='img-box'> <img /> //position absolute <img /> //position absolute <img /> //position absolute <img /> //position absolute I am struggling to center the images within this div because of their absolute p ...

Ways to retrieve the value of the chosen radio button using Prototype or JQuery

Looking for a way to retrieve the value of the selected radio button using either JQuery or Prototype? Check out this sample form: <label for="deliveryChoice">Courier&nbsp;<b>&pound;3.00</b></label> <input type="radio" ...

What is the best method for showing information beneath each tab?

Here is my CodePen link: https://codepen.io/santoshch/pen/MWpYdXK .tab1border{ border-right: 2px solid #f0f0f0; } .tab2border{ border-right: 2px solid #f0f0f0; } .tab3border{ border-right: 2px solid #f0f0f0; } .tab4border{ border-right: 2px soli ...

Ending a session in JavaScript using session_destroy()

I am seeking a JavaScript code that can automatically end the session of inactive users on a live chat website. The website tracks user activity every 5 minutes and updates the database with a timestamp of their last activity. For example, if a user has n ...

Issue with AngularJS: Not able to get second app in template to function properly

I have encountered a puzzling issue with my two nearly identical apps. The first one seems to be running smoothly as expected, while the second one doesn't appear to be executing at all. Here is my code (jsfiddle): <div ng-app="passwdtool" ng-con ...

Guide on retrieving inline style that has been overridden by CSS using JavaScript

<div style="background: url(http://www.example.com/image.jpg) center center/cover;"> This specific background image defined inline is being replaced by a rule in an external stylesheet: div { background-image: none !important; } Here's my q ...

"Transforming a static navbar to a fixed position causes the page to jump

Having some difficulty figuring this out. I'm working on a bootstrap navbar that transitions from static to fixed when the user scrolls past the logo at the top. Everything seems to be working fine, except for when the navbar reaches the top, it sudde ...

Learn how to display months on a countdown timer and then customize the format with basic JavaScript for a website

Looking to create a countdown page for the upcoming ICC cricket world cup event that displays the remaining days in two different formats: Format #1: 01 months 10 days 10 hours Format 2: 01 hours 20 minutes 10 seconds (If less than 2 days remain) I curr ...

Creating a line that connects Point A to Point B using HTML, CSS, and JavaScript

Essentially, I am looking to create a line that connects point A (0vh|0vw) to point B (50vh|50vw). Initially, I considered using a div with a border and a 1px height that is rotated to achieve the desired effect. However, the issue arises when the size ...

What is causing the colorful background to not fully cover my page when I make the window smaller?

I'm currently designing a webpage that features a dynamic gradient background. Within this webpage are two columns - one displaying an image of a phone, and the other containing text. In full screen mode, everything looks perfect. The gradient stretch ...

What is the reason for index.html requesting the css or js modules as if they were directories when loading?

I am currently developing a server using expressjs: 'use strict'; var express = require('express'); var logger = require('morgan'); var path = require('path'); var bodyParser = require('body-parser'); va ...

Tips for showcasing the outcome of an SQL query on an HTML page

I need assistance with displaying the output of an SQL query on my website. My server-side is using NodeJs and client-side is VueJs. After querying my database, I received the following result: [ { Time_Stamp: 2019-12-09T11:54:00.000Z, Time_Sta ...

Update information without the need for page refresh

Check out my new Like button: <a class="wst-click" wst-href="{% url 'data:like' content.id %}" href="{% url 'data:like' content.id %}" >{{ data.likes.count }} Like</a> This code enables the 'Like' functionality w ...

Increase the dimensions of the jQuery modal confirmation box

I am working on a jQuery confirmation dialog that displays some details for the user. My goal is to have the dialog adjust its dimensions after the user clicks "YES" to show a smaller text like "Please wait...". How can I dynamically change the size of the ...