Introducing a fresh Backbone object attribute that points to an existing instance property

While working with Backbone/Marionette, I came across something unusual. When I create a new instance of a view with a new collection property and then create another instance of the same view, it seems that the collection property of the second view points back to the first view's instance. Here's an example:

  var CollectionView = Marionette.CollectionView.extend({
    collection: new Backbone.Collection() 
  });

  var view = new CollectionView();

  console.log('view is ', view);
  view.collection.searchTerm = 'test';
  console.log('view.collection is ', view.collection);

  this.region.show(view);

  var view2 = new CollectionView();
  console.log('view2 is ', view2);
  console.log('view2.collection is ', view2.collection);

  this.region.show(view2);

Upon inspecting the logs, you'll notice that there are two different view instances (one with cid: "view2" and the other with cid: "view5"). However, the collection property of the second view contains a property searchTerm with a value of 'test'. One would expect this to be a completely new Backbone collection...

Feel free to check out the Codepen demo here.

Answer №1

It is common behavior.

The collection is only created once, when the extend function is called. All instances simply have a reference to the collection in the prototype of the CollectionView.

If you desire for your view to be instantiated with a new collection each time, you can create an initialize method:

var CollectionView = Marionette.CollectionView.extend({
    initialize: function () {
        this.collection = new Backbone.Collection();
    }
});

var view = new CollectionView();

console.log('view is ', view);
view.collection.searchTerm = 'test';
console.log('view.collection is ', view.collection);

this.region.show(view);

var view2 = new CollectionView();
console.log('view2 is ', view2);
console.log('view2.collection is ', view2.collection);

this.region.show(view2);

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

Is the Site Header displayed depending on the scroll position and direction of scrolling?

On my website, I have a header that I want to hide when the user scrolls down 100px and show again when they scroll up 50px. I attempted to write a script for this functionality, but it doesn't seem to be working as expected. CSS /* This CSS rule w ...

The React Functional Component undergoes exponential re-renders when there is a change in the array

I'm encountering a problem with one of my functional components. Essentially, it maintains an array of messages in the state; when a new message is received from the server, the state should update by adding that new message to the array. The issue ar ...

What is the method for identifying the environment within an Express.js application?

Is there a reliable method for determining the environment in which an expressJS app is currently operating (development, test, production)? I have checked process.env, but found no clear indication of the environment. I know that variables can be set in ...

Is there any method to avoid the hassle of constantly adjusting margins and paddings on my one-page website?

One issue I encountered was that the buttons weren't scrolling me to the top of the anchor, instead scrolling too far into the section due to the fixed navbar overlapping. I tried solving it with margins and paddings but believe there must be a simpl ...

Enhance your Kendo UI File Manager by incorporating image uploading and folder renaming capabilities

Currently utilizing the kendo UI file manager to navigate through my files and images. According to telerik documentation, only the functions to add folders and remove files and folders are supported. However, I am in need of the ability to rename both f ...

What is the process for uploading an HTML input file in segments?

Is it possible to upload the whole file at once like this: myInput.onchange = ({ target }) => { const file = target.files[0]; const formData = new FormData(); formData.append("fileData", file); // ...then I post "formData" ...

The progress bar in Next JS 13 seems to be malfunctioning and is not displaying any

After transitioning to the new Next JS 13 app directory, I encountered an issue where the progress bar at the top does not function when the page loads. In the previous version, Next JS 12, there was a package named nprogress and nextNprogress that simpli ...

Is it possible to clear a div using jQuery and then restore its contents?

In my setup, I have a video player within a div where clicking the play button (.video-play-container) fades in the video, and clicking the close button (.close-video) fades it out. The issue arose when the faded-out video continued playing in the backgr ...

Leveraging AJAX for connectivity to the Twitter API

Considering incorporating Twitter functionality into my web application, I decided to conduct some tests. After researching how to call the search Twitter URL (more information available at: ) in order to retrieve tweets containing specific words or phrase ...

Using node.js to submit a form and upload an image

Seeking some assistance as a newcomer to node. I am trying to achieve a task without the use of any other frameworks like Express. Here is the scenario: I have created a form where users can upload photos to a server running on a node. The form contains t ...

In my sequence of Promises, a "reject is not defined" error led to the rejection of a Promise

In my code, I set up a chain of Promises like this: let promise = new Promise((resolve, reject) => { imgToDisplay.onload = () => { resolve(imgToDisplay.width); } }) .then((result) => { window.URL.revokeObjectURL(imgToD ...

There was an error while parsing JSON on line 1, where it was expecting either a '{' or '[' to start the input

I've been struggling to extract data from my PHP array that is encoded using json_encode. I'm new to JQuery and have been attempting this for a few days without success. This code snippet is not producing the desired results: $.post('coord ...

AngularJS Toggle Directive tutorial: Building a toggle directive in Angular

I'm attempting to achieve a similar effect as demonstrated in this Stack Overflow post, but within the context of AngularJS. The goal is to trigger a 180-degree rotation animation on a button when it's clicked – counterclockwise if active and c ...

Mean stack authentication issue: missing token

Overview: Currently, I'm in the process of developing an application that utilizes node/express for the backend, mongo as the database, and angular for the frontend. User authentication is handled through jsonwebtoken, where a token is stored in local ...

What is the process for choosing every child (regardless of level) of a parent using jQuery?

Is there a way to unbind all elements from a parent node using jQuery? How can I effectively select all children, regardless of their nesting level, from a parent node? I attempted the following: $('#google_translate_element *').unbind('c ...

Problem with sidebar animation: Functioning properly when open, but closes abruptly without animation in React using Tailwind CSS

When interacting with my Menu react component by clicking on the 'hamburger' icon that I created manually, the sidebar menu opens smoothly with an animation. However, the issue arises when trying to close the sidebar as it vanishes instantly with ...

A ReactJS Error occurred: {error: 400, reason: "Failed match", message: "Failed match [400]", errorType: "Meteor.Error"}

I encountered an issue while attempting to send form data to the server when clicking on the Next Button in a Wizard Form. The error that occurs is related to an "Undefined User" warning displayed in the Console during Step 1 of the form submission: " { ...

Improving the way text entered in an input box is displayed using HTML table cells

Seeking advice on how to display the last two input boxes in a dynamic HTML table so that users can easily view the data they have entered. The issue arises when the length of the data in these columns is large, making it difficult for users to see all the ...

Continuous loop of images displayed in a slideshow (HTML/JavaScript)

Greetings everyone, I am currently working on creating an endless loop slideshow of images for my website. Despite researching several resources, I am still struggling to get the code right. The issue I am facing is that only the image set in the HTML code ...

Personalize your message in a JavaScript alert using Bootstrap notifications

On numerous websites, a new visitor landing on the page is greeted with an alert notification that pops up in either the bottom right or left corner. The code below functions perfectly fine, except for my unsuccessful attempts to change the message text w ...