Callbacks associated with saving Backbone models are not properly executing

I am working on a small application with a model named JobStatuses in Backbone/Express that needs to be synchronized occasionally. According to the Backbone documentation:

save method allows success and error callbacks in the options hash, which will receive the arguments (model, response, options). In case of server-side validation failure, it should return a non-200 HTTP response code along with an error response in text or JSON format.

However, even though the server returns a status code of 200, my success/failure callbacks are not being triggered when I call JobStatuses.save. I have provided the code for my view, model, and route with the server-side handler function. The updateJobs function is the one that is being called. Can someone explain why the JobStatuses.save callbacks are not being triggered?

Below is the view responsible for triggering JobStatuses.save. I can confirm that the render function is called successfully here.

reqs = ['jquery', 'backbone', 'underscore', '../models/jobstatuses']
define(reqs, ($, Backbone, _, JobStatuses)->
  class ButtonView extends Backbone.View
    el: $('.button-container'),
    template: _.template($('#button-template').html())
    constructor: ()->
      this.listenTo(JobStatuses, 'sync', this.render)
      this.listenTo(JobStatuses, 'save', this.render)
      JobStatuses.fetch()
    render: ()->
      this.el.html(this.template(jobStatuses: JobStatuses.attributes))
      this.buttons = this.el.find('.job-button')
      this.buttons.click(()->
        category = $(this).attr('category')
        job = $(this).attr('job')
        JobStatuses.attributes[category][job] = 'Completed'
        JobStatuses.save(
          success: (() ->
            console.log('statuses')
            console.log(JobStatuses.attributes)),
          error: (()->
            console.log('failure'))
        )
      )
)

The JobStatuses model:

define(['backbone'], (Backbone)->
  class JobStatuses extends Backbone.Model
    url: '/jobs'

  new JobStatuses
)

My route. Only the updateJobs function is called:

/*
 * GET home page.
 */
var RUNNING = 'Running';
var COMPLETED = 'Completed';
var BLOCKED = 'Blocked';
var NOT_STARTED = 'Not started';

var jobs = {
  'oon': {
    'oonload': NOT_STARTED,
    'oonstagecopy': NOT_STARTED
  },
  'icd': {
    'icdload': NOT_STARTED,
    'icdstagecopy': NOT_STARTED
  }
}

exports.index = function(req, res){
  res.render('index', { title: 'Backbonejs Batchstart' });
};

exports.getJobs = function(req, res){
  //res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify(jobs));
};

exports.updateJobs = function(req, res){
  jobs = req.body;
  console.log(req.body);
  console.log(jobs);
  res.send(JSON.stringify(jobs));
};

Answer №1

Consider removing the unnecessary parentheses around your success and error functions:

success: (() ->
        console.log('statuses')
        console.log(JobStatuses.attributes)),

Instead, use:

success: () ->
        console.log('statuses')
        console.log(JobStatuses.attributes)

It seems like the issue lies in your save call where you need to specify what needs to be saved. If you just want to update the model based on its current changed state, call save with an empty object like this:

JobStatuses.save({},

Another option is to include the attribute change in the save call like this:

JobStatuses.save(
  category: job: 'completed'
,
  success: () ->

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

"Despite the null date in Node.js, the validation for expiration dates less than Date.now() is still being enforced

I am currently working on implementing validation for evaluating the finish status. However, my validation is encountering a problem with the "null" value of expiresAt. It should indicate that the evaluation has been successfully completed. The issue lie ...

Creating a Validation Form using either PHP or JavaScript

I need to create a form with the following columns: fullname, email, mobile, and address. If the visitor fills out the mobile field, they should only be allowed to enter numbers. And if the visitor fills out the email field, they should only be allowed to ...

Converting server scripts into ES6 with the integration of socket.io

We're diving into socket.io and express as beginners, and we've been following this tutorial to grasp socket.io: Now, we're trying to convert this line of code (using the old style): const index = require("./routes/index").defaul ...

"Troubleshooting the path problem in Vue.js router version 3.0.1

Encountered an unexpected issue and seeking assistance for resolution. Below is a snippet of the route configuration that I am currently dealing with: routes: [ { path: '/signin', name: 'signin', component: SignIn }, ...

Enhance my code to eliminate repetitive elements

Check out this unique plant array: export const uniquePlants = [ { name: 'monstera', category: 'classique', id: '1ed' }, { name: 'ficus lyrata&ap ...

I am hoping for JavaScript to perform three distinct actions depending on the names of the files that are currently open in Photoshop

Currently, I am in the process of developing a JavaScript script for Photoshop. The main objective of this script is to prompt the user to choose a folder containing multiple files. Subsequently, the script will open each file within the folder and perform ...

Utilizing NodeJS and Express to efficiently share sessions across various routes

I have a Node.js web application built with Express that has multiple routes. These routes need to be able to access and share the session data when interacting with users. The routes are separated into different js files from the main app file, app.js. I ...

When an HTML input button within a table fails to trigger any jQuery function upon being clicked

I currently have a table set up with multiple rows and columns. <table style="width: 100%;" class='table_result'> <tr><td>Text</td><td>Text</td><td>Text</td><td>Text</td> ...

Apply CSS styles from a text area using v-html

I am currently working on developing a unique WYSIWYG application where users have the ability to write CSS in a textarea field and view its direct impact on the HTML content displayed on the page. As I was experimenting with different approaches, I attemp ...

Accessing an array beyond its callback scope

Currently, I am working on creating an array of objects with different key values by utilizing basic web scraping techniques in NodeJS. One challenge I am facing is accessing the 'built' Array outside of its parent function, which you can find he ...

Exploring JSON array handling with jquery

Here is the JSON data I am working with: { "category": { "category_identification": "1", "category_name": "C1", "image_one": "1.PNG", "image_two": "1_.PNG", "logo": "LOGO_1.PNG", "category_description": "DESCRIPTION" }, "responseCo ...

The Vue v-bind:class feature does not always update immediately when the value of the binded object is changed

When utilizing Vue, it seems that developers often use v-bind:class to add dynamic classes to elements. However, in the example below, this method appears to not function as expected. //Html <div id="mainapp"> <span class="star" v-bind:class="{ ...

What is the best way to send a Rails AJAX form upon clicking?

I'm looking to implement AJAX form submission in Rails using a button. Here's my current code: Controller: def list @events = ExternalEvent.all if !params[:city_id].nil? @events = @events.where(city_id: params[:city_id]) end respond ...

What is preventing me from accessing the $sceProvider?

Struggling to implement a filter using $sceProvider to decode HTML tags. Here's my current code structure: myApp.filter('decodeHtml', function($sce) { return function(item) { return $sce.trustAsHtml(item); }; However, upon integrating ...

What exactly sets one string apart from another? (JavaScript)

Is it possible to use JavaScript to detect the specific part of strings that makes them different from each other? For example, consider the following three strings: String1 = "Java1String" String2 = "Java2String" String3 = "Java3String" If String1 is t ...

What is the best way to create a reusable component for a dialog box or modal window?

I have been working on developing a reusable dialog component with a yes or no button at the bottom. The main idea behind this is to create a user confirmation dialog that prompts the user to confirm their entered information before proceeding. import Re ...

Textbox with Placeholder Text and Entered Data

When working with an HTML input box to enter a value that will be used to run a PHP script, it is possible to pass that value using the URL and GET method. To enhance user experience, I wanted to add a watermark hint in my textbox. After some research, I ...

I'm confused as to why the icon color isn't changing on the Blogger homepage for each individual user

I'm experimenting with changing the eye color based on visitor count. It works perfectly fine on static posts in my Blogger, but it fails to update the eye color properly on my homepage according to the set numeric values. Instead of displaying differ ...

Unable to retrieve data from response using promise in Angular 2?

I am struggling to extract the desired data from the response. Despite trying various methods, I can't seem to achieve the expected outcome. facebookLogin(): void { this.fb.login() .then((res: LoginResponse) => { this.acce ...

Apply a watermark specifically to fancybox for images in galleries, excluding non-gallery items

I recently encountered an issue with a FancyBox image gallery on my webpage. I wanted to add a watermark to the gallery items, so I followed an example from the FancyBox page at http://jsfiddle.net/w5gQS/. beforeShow: function () { $('<div class=" ...