Creating an HTTP interceptor in Backbone: A step-by-step guide

After gaining experience with backbone, I decided to delve into learning angular. The features of angular really caught my interest, especially the HTTP interceptor. I began thinking about how to implement this functionality in backbone to display a spinner and toaster notifications while data is being saved or fetched from the back-end using AJAX. With some exploration, I managed to find a solution. I wanted to share it in the hopes that it will benefit others as well.

Answer №1

Assuming you are implementing requireJS; if not, convert AMD to IIFE

define("vent", ["backbone", "backbone.marionette"], function(backbone) {
    return new backbone.Wreqr.EventAggregator
});
define("backbone-sync", ["backbone", "underscore", "vent"], function(backbone, underscore, vent) {
    var xhrArray = [];
    var stopAllRequests = function() {
        underscore.invoke(xhrArray, "abort"),
        xhrArray = []
    };
    // specify the text to display on spinner and toaster based on options
    var displaySpinnerAndToaster = function(method, options) {
        if ("create" === method || "update" === method || "patch" === method) {
            // show saving spinner
        }
        if ("read" === method) {
            // show fetching spinner
        }
        this.once("sync", function() {
            // hide spinner and show success toaster
            delete this.cancelRequest;
            this.off("error");
        });
        this.once("error", function(model, xhr) {
            // show error toaster if xhr.statusText !== "abort"
            delete this.cancelRequest;
            this.off("sync");
        });
    };
    vent.on("stopAllRequests", stopAllRequests);
    backbone.Model.prototype.sync = backbone.Collection.prototype.sync = function(method, model, options) {
        var displaySpinnerAndToasterProxy = underscore.bind(displaySpinnerAndToaster, this);
        displaySpinnerAndToasterProxy(method, options)
        var xhr = backbone.sync.apply(this, arguments);
        xhrArray.push(xhr);
        xhrArray = underscore.reject(xhrArray, function(xhr) {
            return 4 === xhr.readyState
        }),
        this.cancelRequest = function() {
            xhr.abort();
        }
        return xhr;
    }
});

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

Master the Art of Scrollbar Control in Angular!

I am currently developing a chat web application that functions similar to gchat. One of the key features I'm trying to implement is an alert notification when the scrollbar is in the middle of the div, indicating a new message. If the scrollbar is at ...

Deleting files with a dedicated function (Dropzone.js)

I need to implement functionality that removes the uploaded file when a 'cancel' button is clicked. Here's how my HTML code looks: <div reqdropzone="reqDropzoneConfig"> <form id="requisitionupload" class="dropzone dz-clickable" ac ...

How can I effectively display a blank menu item for the SelectField component in Material-UI within a React application?

I am using the select-field component from the material-ui framework version 0.15.4 with React version 15.4.0. I am attempting to add a blank menu-item to the select-field in order to allow for deselecting a value in the dropdown field when clicked. Howeve ...

What could be the reason my node.js application built with express is unable to retrieve data from mongoose

Currently, I have experience in PHP MVC and recently delved into learning Nodejs. Here is how my app directory structure looks like: root - controllers -user.js - model -user.js - public -stylesh ...

The scope of this variable in Node.js results in an undefined response

Have you ever noticed the difference in behavior when executing JavaScript code in Google Chrome's console compared to running the same logic in a file using Node.js? function foo() { console.log( this.bar ); } var bar = "global"; foo(); In Chr ...

What is the best way to retrieve data input from my select dropdown?

I have a select menu generated from a database and I want to display the value of the selected option in an input field. Currently, my code only shows the value of the first option. How can I modify it to display all selected values? Thank you. <?php ...

ReferenceError: _jquery2.default.ajax is not a function" encountered in a React Native application

I have been attempting to use jQuery to retrieve xml data from an internal website. My expo project setup is quite basic and resembles the following: import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; imp ...

Sending fragmented files straight to Amazon's s3

Currently seeking straightforward examples of uploading directly to Amazon s3 in chunks without any server-side processing, except for signing the request. I have explored various options, but all examples I have found either focus solely on chunking from ...

Rendering a Subarray using Map in ReactJS

I have an object containing data structured like this: [{"groupid":"15","items":[ {"id":"42","something":"blah blah blah"}, {"id":"38","something":"blah blah blah"}]}, {"groupid":"7","items": [{"id":"86","something":"blah blah blah"}, {"id":"49","somethin ...

Trouble with radio button selection in Pyppeteer, puppeteer, and Angular JS

I am struggling to select the 'fire' option in a radio button within a div element using Pyppeteer. Despite multiple attempts, I have not been successful. Here is the structure of the div with the radio button: <div _ngcontent-xqm-c396=" ...

Encountering a 422 ERROR while attempting to send a POST request

Below is the code snippet I am currently using: const url = new URL("https://api.chec.io/v1/products"); const headers = { "X-Authorization": `${process.env.NEXT_PUBLIC_CHEC_PUBLIC_KEY_SECRET}`, "Accept": "appl ...

Error Encountered when Using JQuery AJAX: Unexpected Identifier Syntax Issue

I've been struggling with a strange error for quite some time now. I want to believe that this is one of those errors where the solution will magically appear, but only time will tell. Here's the piece of code causing the issue: var images = ...

Is it possible to achieve dynamic updating in Angular without utilizing ng-repeat? (with the use of Firebase)

Is there a way to dynamically update the DOM without utilizing ng-repeat in your template? It appears that when using ng-repeat to load a list of objects, any additions or deletions from the database automatically reflect in the DOM. However, if I simply u ...

The declaration file for the 'react' module could not be located

I was exploring Microsoft's guide on TypeScript combined with React and Redux. After executing the command: npm install -S redux react-redux @types/react-redux I encountered an error when running npm run start: Type error: Could not find a decla ...

Obtain an individual item from the reducer array

I am working on a company reducer that will store an array of companies. To optimize performance, I aim to fetch only the necessary company object from my API when a user navigates to /company/name. This way, if a user visits the same company page multiple ...

"Enhance your data visualization with Highcharts Windbarb and effortless AJAX data

Alright. Let's rephrase a question that hasn't been answered yet. I've got a chart below with data loading dynamically via ajax. A simplified version (without ajax) of this graph works well as shown in this jsfiddle. The code below represe ...

What is the best way for me to incorporate images retrieved from an API call into my

Hey everyone, this is my first time posting on here so if there's anything I'm missing, please let me know! I've run into an issue with the images on my categories page not aligning properly and being different sizes after I incorporated som ...

No response data being displayed after Angular post request

After sending a POST request via Postman, I received the expected response with a status of 400. However, when I tried sending the same request using Angular's http.post in the browser, I only received a 400 error without any response data. https://i ...

Axios removes the async functionality

Is there a way to achieve the same functionality without using the async function? async EnvioLogin() { const response = await axios.post("api/auth/login", { email: this.email, password: this.password, }); localStorage.setItem(" ...

Creating a JSON object hashtable using jsHashtable: A step-by-step guide

I have a good understanding of how to create a hashtable from scratch using jshashtable. For instance: <script type="text/javascript" src="jshashtable.js"></script> <script type="text/javascript"> var typesHash = new Hashtable(); ...