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

What is the best way to recover accented characters in Express?

Encountering issues with accented characters in my POST request .. I attempted using iconv without success.. Snippet of my code: Edit: ... var bodyString = JSON.stringify(req.body); var options = { host: XXXXX, port: XXX, ...

Update search results when performing a new search on a web application (without using jQuery)

My simple web app interacts with an API to retrieve search results from a database and utilizes ajax to insert them into an empty ul element on the page (employing JSONP for cross-domain requests). I am struggling to achieve this functionality using plain ...

The AJAX Request has indicated that the entity provided is not in an accurate 'application/json' format. It seems to be missing or empty, leading to an error with a code of '400'

While attempting to create an AJAX request to submit users to an external API, I faced a problem that is hindering my progress. Since I'm more familiar with PHP than JS, I saw this as an opportunity to expand my knowledge in JavaScript. The approach ...

Creating custom ExpectedConditions with Protractor for detecting attribute changes

I've been working on creating a custom ExpectedConditions method that can wait for an element attribute to change. Here is the approach I came up with: const CustomExpectedCondition = function() { /** * Check if element's attribute matches ...

Troubaling with AngularJS Routing issues

I am encountering an issue with my routing system. The "otherwise" case is functioning correctly, however, when I click on a menu item, the routing does not load the corresponding page automatically. Can someone assist me in identifying what is wrong with ...

Using NodeJs to pass values to a callback within a condition statement and retrieve the returned value

Within my routing file, I have implemented a condition where an external function is used to compare two values: obj.id === getId. Based on whether this condition evaluates to true or false, the view is rendered, or the user access is blocked. The functio ...

When the enter key is pressed, the form will be automatically submitted

My current implementation includes the utilization of Bootstrap input tags as shown below: myPage.html <form th:object="${field}" name="modal" method="post" th:action="@{/ajouterFieldEcran}"> ... <div class="form-group row"> <label ...

Determine the percentage using jQuery by considering various factors

I am facing an issue with the following code snippet: <script type="application/javascript"> $(document).ready(function () { $("#market_value").on("change paste keyup", function() { var market_value = par ...

jQuery - contrasting effects of the before() and after() functions

I'm working with a sortable list that is not using jQuery UI sortable, but instead allows sorting by clicking on buttons. Sorting to the right using after() works perfectly, however, sorting to the left with before() is causing issues. First, here&ap ...

The functionality of the button is affected when it is placed on the same line as a h1 heading

My goal is to have the page title and profile button aligned on the same line in the header of each page. However, I've encountered an issue where the button doesn't function properly when placed on the same line but works fine when separated ont ...

Continuous Playback of Sound

Is there a way to autoplay an audio in loop without being blocked by browsers? Code : <audio id="audio1" src="assest/sound/1.mp3" autoplay="" /> <script> a = document.getElementById('audio1&apo ...

Are there any alternative methods for clearing form fields following a successful thunk dispatch in React?

When implementing a Post API call in Thunk, I dispatch a boolean success key for successful requests and an error message for errors. Now the goal is to clear form data upon success and display the error message upon an error. To achieve this, I utilize ...

How can you prevent the 'Script not responding' error when using Reverse AJAX / Comet?

My worker thread is responsible for sending requests to the server using XMLHttpRequest. The request is directed to a php file which checks the integrity of client information. If the client requires new data, it is sent. Otherwise, the server continuously ...

Challenges with the jScroll Plugin

Trying to implement jScroll to load a partial view multiple times using an increasing page number. The partial view returns a few divs. To achieve infinite scrolling, the partial view needs to have a hyperlink tag that directs to the next page to load. Th ...

Tips for connecting 2 Bootstrap 5 carousels

I currently have 2 Bootstrap 5 carousels (carousel-a & carousel-b) on the same page and I want them to be synchronized with each other. I believe this can be achieved using JavaScript, but I am not very familiar with it. Below is the structure of carousel- ...

Transform a list of H1..6 into a hierarchical structure

I have a task to convert H1 to H6 tags from a markdown file into a JavaScript hierarchy for use in a Table of Contents. The current list is generated by AstroJS and follows this format [{depth: 1, text: 'I am a H1'}, {depth: 2: 'I am a H2}] ...

Using a text box in jQuery to perform basic calculations is a straightforward process

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Creating a Lens Calculator Web App</title> <link href="http://code.jquery.com/mobile/1.0a3/jque ...

Link the values of mongoose array to a distinct identifier

This question may come across as vague, but I'll do my best to explain it clearly. Just a heads up, I'm relatively new to working with mongoose :) So, I have this mongoose schema where different values are stored for each user: let userSchema = ...

Utilizing the state as a condition within the useEffect to update the component

Is there a way to automatically hide the mobile menu when the URL changes in ReactRouter? I have noticed that I get a warning for not tracking mobileOpen as a dependency, but strangely the code still works fine. const Navbar: React.FC<Props> = props ...

Is it possible to modify the express static directory path depending on the route being accessed?

I am trying to dynamically change the static path based on the route. Here is an example of what I have tried: const app = express(); const appRouter = express.Router(); const adminRouter = express.Router(); appRouter.use(express.static('/path/to/ap ...