The event listener attached to this model is failing to trigger when there are

The issue is that the "change" event is not being triggered in the code snippet below.

var PageView = Backbone.View.extend({
    el: $("body"),
    initialize: function(){
        this.model.on("change:loading", this.loader, this);
    },
    loader: function(){
        if(this.model.get("loading")){
            this.$el.find('.loader').fadeIn(700);
        }
        else 
            this.$el.find('.loader').fadeOut(700);
    },
});

var PageModel = Backbone.Model.extend({
    defaults: {
        loading: null,
    },
    initialize: function(){
        this.set({loading:false});
    },
});

$(function(){
    var pageModel = new PageModel({});
    var pageView = new PageView({model: pageModel});
})

A workaround for this issue is to add the following code inside the model's initialize function:

 setTimeout(function() {
     this.set({'loading': 'false'});
 }, 0);

Although this temporarily resolves the problem, it is essentially a bug that needs to be addressed.

Answer №1

The breakdown of the scenario

Let's dissect how the code sequence unfolds:

  1. First, the model is initialized,
  2. Next, the model's initialize function is executed, setting the loading attribute to false,
  3. Then the model is handed over to the view,
  4. A listener for the "change:loading" event is registered

However, the event handler remains inactive because the specified event never occurs after registration.

Solution at a glance

To resolve this issue promptly, eliminate the set action from the model.

var PageModel = Backbone.Model.extend({
    defaults: {
        loading: null
    }
});

Subsequently, post creating the view, manipulate the loading attribute.

var pageModel = new PageModel();
var pageView = new PageView({ model: pageModel });

pageModel.set('loading', false); // This adjustment should trigger the event now

By ensuring that the listener is established before altering the model's loading attribute, the event handler will be invoked successfully.

An enhanced approach

Adhere to Backbone's recommended methodologies:

  • Prioritize .listenTo instead of .on to prevent memory leakages
  • Cache jQuery objects effectively
  • Aim to avoid configuring the el property within the view

A view serves as an independent unit focusing solely on its components and sub-views.

In your specific scenario, though using the el property in the view isn't detrimental, it still extends beyond the expected duties of the view. Delegate the responsibility of designating the element to utilize for this view to the calling script.

var PageView = Backbone.View.extend({
    initialize: function() {
        this.model = new PageModel();
        this.$loader = this.$('.loader');
        this.listenTo(this.model, "change:loading", this.loader);
    },
    loader: function() {
        this.$loader[this.model.get("loading")? 'fadeIn': 'fadeOut'](700);
    },
    render: function() {
        this.loader();
        return this;
    }
});

Place the default values where they belong.

var PageModel = Backbone.Model.extend({
    defaults: {
        loading: false
    }
});

In this case, we designate the body as the chosen element for the view by utilizing the el option, followed by invoking the render function once prepared.

$(function() {
    var pageView = new PageView({ el: 'body' }).render();
});

The listener won't respond immediately to the event; instead, we employ the render function to establish the view in its default state. Subsequent modifications to the loading attribute will then activate the callback.


I've compiled a list of the most valuable information I've shared concerning Backbone on my profile page. I recommend exploring it, covering everything from fundamental concepts to advanced techniques, including some ingenious Backbone components for addressing common issues (such as identifying clicks outside a view).

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

Tips for passing an object as an argument to a function with optional object properties in TypeScript

Consider a scenario where I have a function in my TypeScript API that interacts with a database. export const getClientByEmailOrId = async (data: { email: any, id: any }) => { return knex(tableName) .first() .modify((x: any) => { if ( ...

What is the process by which JavaScript evaluates the closing parenthesis?

I'm currently working on a calculator project that involves evaluating expressions like (5+4). The approach I am taking is to pass the pressed buttons into an array and then create a parse tree based on the data in that array. One issue I'm faci ...

Struggling to implement Datatables row grouping using ajax is proving to be quite challenging

Is there a way to group rows in a table based on date ranges, using the data from the first column ("Due_Date"), and leveraging the rowGroup extension provided by Datatables? I've tried various solutions found online, such as using the data property ( ...

Receiving a blank string after calling fs.readFile within the chokidar.watch(path_file).on('change', ...) function

This is my current Node project setup: https://github.com/tlg-265/chokidar-issue https://i.stack.imgur.com/qYKlR.png $ git clone https://github.com/tlg-265/chokidar-issue $ cd chokidar-issue $ npm i $ npm run watch-changes The project monitors changes ...

Step-by-step guide for launching a Next.js/Node application

Currently, I am developing a full-stack project utilizing a next.js application for the front-end and a node/express server for the API. The front-end and back-end are running on separate ports. Here is how my application is configured: https://i.stack.im ...

What is the method to access and examine the attributes of a range in Office.js?

I am encountering an issue while attempting to retrieve the values from cell B2 and create a conditional statement based on those values. Despite my efforts, I continue to receive an error message without any clear understanding of its cause. Please refe ...

Problem with onblur and onchange events not being triggered in input tag

After encountering this issue, I came to the realization that the events onblur and onchange function properly. However, I noticed that if your page contains only ONE <input type="text" onblur="loadXMLDoc()"> Change Content</input> The behav ...

Error: An unexpected 'if' token was not caught

Encountering an error related to the question title while working with this code snippet: $LAB.queue(function setup() { FB.init({ appId: '00000000', status: true, cookie: true, xfbml: true, logging: &ap ...

What is the method for inserting JSON data into a select element's options?

Below is the HTML code snippet provided: <html> <head> <link rel="stylesheet" type="text/css" href="CarInfoStyle.css"> </head> <script src="CarInfoJavascript.js"></script> <body> <div class="search ...

"Discovering a button press using the Gamepad API: A Step-by-Step Guide

I'm currently building a web page that can detect button presses on an Xbox controller and display a boolean value based on the pressed button. Right now, I have successfully managed to detect when a controller is connected and show it as a string. Ho ...

Investigating unsuccessful requests in node.js

Here is my code: var request = require('request'); function Service(){ this._config = require('../path/to/config.json'); } Service.prototype.doThing = function(){ return new Promise(function(resolve, reject){ request.post(url, ...

Filtering data with React's multiselect checkboxes

I have created an amazing app that fetches a list of todos from this incredible source To enhance user experience, I developed a special CheckBoxDropDown component for selecting todo IDs Within the CheckBoxDropDown.js component, I am passing the onChange ...

Executing a scroll down action with Selenium in combination with Node.js and the Chai/Mocha testing framework

Browser: Chrome Looking for ways to scroll up or down using Selenium with Node.js (JavaScript). ...

Getting the Request Body Content in Express Middleware

Currently, I am in the process of developing a small API logger to use as an Express middleware. This logger is designed to gather data from both the request and response objects, then store this information in a JSON file on disk for later reference. Her ...

"In the shadows, the .toLowerCase() method of undefined is failing without making a sound, yet the code

It seems that letting things fail in the background is necessary for this example to work consistently. Is there a way to work around this issue? There are instances where I need to check a div with a data-attribute on certain pages and add a class if it ...

Mapping various sets of latitudes and longitudes on Google Maps

I am working with multiple latitude and longitude coordinates. var latlngs = [ {lat:25.774252,lng:-80.190262}, {lat:18.466465,lng:-66.118292}, {lat:32.321384,lng:-64.757370}, {lat:25.774252,lng:-80.190262}, ]; The coordinates were ret ...

Switching between numerical and alphabetical input using JQuery

How can I switch between allowing character and numeric input in a textbox? I currently have a JQuery function that restricts input to numbers only $('.numeric').on('input', function (event) { this.value = this.value.replace(/[^0 ...

Express 4 does not support Angular ngRoute

I am trying to set up client-side routes using Angular along with Express 4. I have successfully used the ngView directive as per the guide ngView without Express, but once I enable Express routing, ngRoute stops working. How can I configure Express to wor ...

Node's getRandomValues() function is throwing an "expected Uint8Array" error

Currently, I am experimenting with the getRandomValues() function to enhance an encryption REST API that I am developing for practice. My server is using Node, which means I do not have access to a window object containing the crypto object normally housin ...

Highcharts introduces shared tooltips for specific data series

I am seeking to implement specific behavior in highcharts regarding tooltips. The desired setup includes having two types of tooltips: the default shared tooltip a custom tooltip For the custom tooltip, a simple formatter can be utilized. However, the c ...