Events from Backbone are not passed along to a newly created element following the setElement method

I am in the process of creating a Backbone view using an Underscore template. I am utilizing the setElement function to replace the view el with the template html, as stated in the function's declaration that it should "...move the view's delegated events from the old element to the new one". However, for some reason, this functionality does not seem to be working correctly. Can anyone provide insight into why this is not functioning as described in the Backbone declaration?

Here is an example illustrating the issue (relevant sections of the view):

     initialize: function(args) {
        _.extend(this, args);
        this.listenTo(this.model, 'change', this.render);
     },

     events: {
        'click .active-area': '_test'
     },

     _test: function() {
        // The event doesn't trigger after "setElement" is called.
        this.model.set('color', 'green');
     },

     render: function() {
        // The "click" listener no longer works after this point.
        this.setElement(this.template(this.model.toJSON());

        return this;
     }

Answer №1

this.template(...) is not a part of the document object model.

In your code, setElement removes the event listeners from the old element and assigns them to the new element, which only exists in memory, not on the actual page.

Instead of replacing the entire element, you should simply update the content of the current element.

this.$el.html(this.template(this.model.toJSON()));

I need to swap out the entire element's HTML with the template HTML, hence why I am using the setElement function.

Assume you have this HTML structure:

<div id="currentView"><!-- view's root (el) -->
    <button type="button" class="active-area">Click me</button>
    <span class="color"><%= color %></span>
</div>

Add a wrapping div and place the #currentView div within the template.

<div class="wrapper"><!-- view's root (el) -->
    <div id="currentView">
        <button type="button" class="active-area">Click me</button>
        <span class="color"><%= color %></span>
    </div>
</div>

Now, calling this.$el.html will replace the complete element.


If you do need a view to switch its root element, you can construct a new element and employ jQuery's replaceWith method to substitute the old element with the new one.

render: function() {
    // create a new element using the template
    var $newEl = $(this.template(this.model.toJSON()));

    // entirely swap out the current element in the DOM
    this.$el.replaceWith($newEl);

    // inform the view accordingly
    this.setElement($newEl);

    return this;
}

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

Encountered a Uncaught TypeError: Attempted to clear a canvas when the property 'getContext' is undefined or null

After researching multiple error solutions, none seemed to work for me. It became frustrating, leading me to consider spamming just to bypass the word limit and share my own findings with others facing similar issues. Check out the Answers section below to ...

Ways to properly link a webpage using the anchor tag's href attribute

I am currently working with reactjs and bootstrap, and I am trying to display and collapse an unordered list within a list item (nested unordered list). Bootstrap provides a useful collapse feature for this purpose. By using an anchor tag with a data-toggl ...

Managing key presses with functions in VueJs

Within my component, I am utilizing VueStrap's modal in the following manner: <template> <modal-window v-model="show" v-on:keyup="keyHandler($event)" @ok="submit()" @cancel="cancel()" @closed=" ...

Calculate the total amount from the selected items on the list, depending on the clicked ('active') element

My main objective is to achieve the following: Before any clicks || After the user selects the desired item After conducting some research, I successfully implemented this using vue.js https://jsfiddle.net/Hanstopz/Lcnxtg51/10/ However, I encountered ...

Unable to generate a new file via POST request in mongoose and express

Can someone please review my Node.js code? I am trying to save contact page data in Mongoose Compass. The code runs without any errors, but it's not saving the data. <form action="/" class="contact_form grid" method="POST& ...

Opening a new tab on any webpage with C# Selenium

Is there a foolproof way to open a new tab when using Selenium? Trying to use an action method has proven unsuccessful Actions a = new Actions(driver); a.KeyDown(OpenQA.Selenium.Keys.LeftControl); a.SendKeys("t"); a.KeyUp(OpenQA.Selenium.Keys.L ...

Stripping double quotes from json output

Using a basic array to reference icons like so: {name: "text", avatar: srcs[15]} has been working perfectly. However, I am now dynamically creating an array from my JSON API, resulting in an array of objects structured like this: {name: "text", avatar: ...

A guide to effortlessly converting Any[] to CustomType for seamless IntelliSense access to Properties within Angular/Typescript

Our Angular service interacts with the backend to retrieve data and display it on the UI. export interface UserDataResponse { id: number; userName: string; } AngularService_Method1() { return this.http.get<UserDataResponse[]>(this.appUrl + "/Ap ...

Enrich your HTML using AngularJS

CSS <div class="container"> <section> <p>{{content}}</p> </section> </div> script.js (function () { var script = function ($scope){ $scope.content = "example"; } }()); I am currently ...

The AngularJS directive seems to be having trouble receiving the data being passed through its scope

Check out this HTML code snippet I created: <div ng-controller="ctrl"> <custom-tag title = "name" body = "content"> </custom-tag> </div> Take a look at the controller and directive implementation below: var mod = angular.mod ...

Combine various hierarchies using a single JSON with d3.pack

I currently have a JSON file that I need to utilize in order to create three distinct hierarchy visualizations using d3.pack. This JSON file contains data for eventA (1 or 0) and eventB (1 or 0). Each individual leaf also possesses a unique ID. The hiera ...

Can the Three.js WebGLRenderer be utilized on a node.js server environment?

There seems to be conflicting opinions on whether running WebGLRenderer on the server is feasible. Some say it can't be done, while others claim they are making efforts to achieve it but haven't succeeded yet. Is there a way to accomplish this? ...

When selecting the "Open Link in New Tab" option in Chrome, the Angular app's routing will automatically redirect to the login page

I am facing a peculiar issue in my Angular 2 application that I need help troubleshooting. Currently, the routing within my app functions as intended when I click on links to navigate between different components. Here is an example of how the routing path ...

How come my attempts to make my jQuery fade in upon button click aren't working?

#rock { display: none; position: relative; left: 49.4% } #paper { display: none; position: relative; left: 49%; bottom: 81px; } #scissors { display: none; position: relative; left: 48.14%; bottom: 162px; } #shoot { display: none; ...

How can I modify the fill color of a Cell when hovering over a Bar Chart in Recharts?

I have been rendering the chart in the following manner: <BarChart width={868} height={40} data={data} margin={{top:0, bottom: 10, left:0, right:0}} barSize={5}> <Tooltip labelStyle={{ textAlign: &apo ...

Initializing start scripts in the package.json file

When launching my react app locally, I need to execute three commands: cd react-web npm run postinstall export REACT_APP_CUSTOMER_ENVIRONMENT=xxx npm start After running these commands, the application server starts on localhost:3000. For the start script ...

Using a Chrome Extension to interact with the DOM of the popup.html page and successfully implementing jQuery functionality

As a novice in the realm of Chrome Extension development, I am currently facing two challenging obstacles: The first hurdle is accessing the DOM of my popup.html file, the foundation of my extension. I've attempted various methods including inline ...

Using Ruby on Rails to incorporate AJAX for posting and commenting functionality

Could use some assistance with implementing AJAX into my project. It seems like it should be a simple task, but I've been struggling with it for days. My goal is to have new comments appear without the need to reload the page. Below are references to ...

Discover the route followed by an object containing a specific key within an array of objects

Imagine having an array of dictionaries like the one below. How can I locate the object with id: 121 using JavaScript? I've been struggling to figure this out and would appreciate any hints or algorithms on how to achieve this. The desired result sho ...

Why is JavaScript globally modifying the JSON object?

I have a few functions here that utilize the official jQuery Template plugin to insert some JSON data given by our backend developers into the variables topPages and latestPages. However, when I use the insertOrHideList() function followed by the renderLis ...