The Backbone model destruction URL fails to include the model's ID when trying to delete

I'm facing an issue in my app where I need to delete a model from a collection using "this.model.destroy" in my view, but it triggers a 405 response and the response URL doesn't include the model's id. According to the Backbone documentation, the URL is supposed to be generated based on "Collection URL + Model ID". I have temporarily fixed the problem by manually passing in the URL to the destroy method, but I know this is not the ideal solution. I believe there should be a better way to handle this without resorting to a hack. The backend requires an ID when sending a DELETE request. What would be the best practice to achieve this using Backbone?

        My.Model._entity = Backbone.Model.extend({

        initialize: function(options) {
            if (options.created && typeof options.created === 'string') {
                this.set('created', new Date(options.created));
            }

            if (options.modified && typeof options.modified === 'string') {
                this.set('modified', new Date(options.modified));
            }
        },

        defaults: function() {
            return {
                created: new Date(),
                modified: new Date()
            };
        }
    });


    My.Model.cartItem = My.Model._entity.extend({

        defaults: function () {
            var _def = My.Model.cartItem.__super__.defaults.apply(this, arguments);
            return _.defaults(_def, {
                description: "",
                title: "",
                image: "",
                price: 0,
                quantity: 0,
                itemId: ''
            });
        },

        url: '/checkout/item'
    });

    My.Collection.CartItem = Backbone.Collection.extend({
        model: My.Model.cartItem,
        url: '/checkout/item'

    });

Answer №1

My solution involved setting urlRoot to a function.

urlRoot: function () {
        return "/purchase/product";
    }

This method enabled the Collection to effectively generate the url.

Answer №2

It is advised that your 'My.Model.cartItem' does not replace the url property with a string, or override it in any way. According to default behavior (referenced here), the model's URL is a function that appends its ID to the collection's base URL (which you have already defined).

If you do need to specify a custom URL path to be added to your model's ID, you can still achieve this by using "urlRoot" instead of "url". However, removing 'url' in this case should work perfectly fine.

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

Retrieve all records from a table using Prisma client

I need to retrieve all data from a table using Prisma. How can I achieve this? (SELECT * FROM application) const applications = prisma.application.findMany({ // Retrieves all fields for the user include: { posts: { ...

Uploading a Node.js Package to GitHub Packages - Issue ENEEDAUTH

Hello everyone, I am currently attempting to deploy my NPM package to GitHub packages using the following yaml configuration: # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created # For m ...

Establish communication between two Sails applications

I am currently working on a Sails.js project that features a member portal with all possible routes and actions. However, I am considering developing a CMS using Sails as well. Originally, my plan was to integrate the CMS into the existing project, but n ...

The elements within the Popup Modal are not displaying as expected

I found a helpful tutorial that teaches how to display a Popup Modal Window when the page loads. However, I'm facing an issue where the modal is not showing the contents and images properly. The code I am working on can be found at jsFiddle. My goal ...

What is the process for setting a personalized title for error pages in Remix?

I'm currently working on setting up the 404 page for my Remix app, but I'm facing challenges when it comes to configuring the <title> meta tag for these pages. Within my root.tsx file, I have defined a MetaFunction and a CatchBoundary: exp ...

Error message "auth/code-expired" is triggered when Firebase Multi Factor Authentication for a web application detects that the verification code has expired

While working on adding multi-factor authentication to my Angular web application, I encountered an error message stating: "auth/code-expired", "The SMS code has expired. Please resend the verification code to try again.", even though I ...

Node.js and the Eternal Duo: Forever and Forever-Montior

Currently, I am utilizing forever-monitor to launch a basic HTTP Node Server. However, upon executing the JavaScript code that triggers the forever-monitor scripts, they do not run in the background. As a result, when I end the TTY session, the HTTP server ...

Is it possible to download multiple files using a single ajax call upon success of a click function?

In my file, there are 2 anchor tags with their respective href links. I am triggering both anchor tags at ajax call success. <a id="exportExcelFatturaIcon" href ="${createLink(action: 'downloadExcel', params: [fileName:excelFileName])}" hidde ...

Steps for adding a forked version of a library in package.json

Recently, I came across a React JS library called React Pacomo. Since the original version of this library is no longer being maintained, I decided to use my own forked version for my project. However, I am facing issues with compiling or building the libr ...

Dragging the world map in D3 causes it to appear jumpy and erratic

I'm currently working on a Vue project to create an interactive world map that allows users to drag and zoom. I've attempted to integrate D3 for this purpose, but encountered an issue where the map jumps to the bottom right of the page whenever I ...

Navigation bar theme toggle malfunctioning as anticipated

I'm experiencing an issue with the navbar theme change functionality. Whenever I click on the dark mode button, the theme changes for a brief moment and then reverts back to light mode. <!doctype html> <html lang="en"> <hea ...

Sending a string parameter from an AJAX function to a Spring controller

I'm currently developing a standalone application and facing an issue with passing a string, which is generated from the change event, to the spring controller using the provided code snippet. Here is the HTML CODE snippet: <!DOCTYPE HTML> < ...

Why isn't my ajax call working after using window.close?

Whenever I click the button on my page, a small window opens and the value from the window is sent to my controller before closing. However, I noticed that when I include the window.close() line, the controller does not get hit. It works perfectly fine wit ...

Conflicting Angular controller names within different modules

I'm facing an issue where two modules (A and B) with controllers of the same name are conflicting when imported into module C. Is there a recommended solution to prevent this conflict, such as using a naming convention like "module.controller" for ea ...

What's the most effective method for implementing dynamic navigation in NextJS using Firebase integration?

Excited to begin building a web app using NextJS and Google's Firebase. This app will have both an admin panel and a public site, with the ability for the admin to edit the navigation of the public site. I'm debating whether it's wise to fet ...

Utilizing Three.js to Upload Images and Apply Them as Textures

While attempting to upload an image via URL and set it as a texture, I encountered an issue. The error message THREE.WebGLState: DOMException: Failed to execute 'texImage2D' on 'WebGLRenderingContext': Tainted canvases may not be loaded ...

AngularJS $http.get request failing to retrieve data

I've been delving into AngularJS lately, but I'm having trouble displaying the data from my MySQL database on the view. Here's the code snippets I'm working with: todoController.js angular .module('todoApp') .control ...

Patience is key while waiting for Meteor.loggingIn() to be false

I need help implementing authentication on a React route using Meteor and React.js. Here is my current approach: <Router history={browserHistory}> <Route path="/vendor/chat" component={VendorChat} onEnter={requireVendorAuth} /> </Route ...

A guide on incorporating a customized Google map into your website

Recently, I utilized the Google Map editing service from this site: https://developers.google.com/maps/documentation/javascript/styling This link provided me with two things: 1. A JSON code 2. The Google API link However, I am unsure about how to incorpo ...

Implementing Dynamic Passing of Link Element Value to a Function in jQuery

I'm working with a link element that has its value set dynamically through asynchronous means. This label's value will initially be null until it is asynchronously set by an ajax call. <a href="#" onclick="myFunction(**I want to pass the lab ...