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

Creating unique identifiers/primary keys for resources in react-admin: A step-by-step guide

I am working on a nextJS project that utilizes redux for state management and an admin panel called react admin. In my project, I decided to use _id instead of id as the keys. To achieve this, I followed the instructions provided in this custom identifiers ...

Load Form with Json Data from LocalStorage Key-ID to Auto-Populate Fields

After successfully setting the ID in localStorage, I now need to retrieve and display only that specific record from my JSON data. The content of my localStorage is: This information is obtained from my JSON data after a button click. The challenge is us ...

Transform the Standard class into a generic one in typescript

I've created a class that can take JSON objects and transform them into the desired class. Here's the code: import {plainToClass} from "class-transformer"; import UserDto from "../../auth/dto/user.dto"; class JsonConverter { ...

Differences between applying addClass(undefined) and addClass(null)

At times, it crosses my mind to include a class in a chain, depending on certain conditions. What would be the most fitting semantic value to add no class? For instance: $(".element").performAction().addClass(condition ? "special-class" : undefined).perf ...

Revamp the component onclick functionality in ReactJS

Within my component, I have an onClick method defined. This method makes a call to the backend and fetches some data. However, the values retrieved from this call are only reflected after refreshing the browser. Is there a way to re-render my component wit ...

Troubleshooting date range validation in jQuery

I am facing an issue in my code where I have a set of start and end date fields that need to be validated to ensure the start date comes before the end date. I am currently using the jQuery validation plugin for this purpose. For reference, here is the li ...

The value of a variable remains constant even when it is assigned within a function

I developed a dynamic image slideshow using HTML and JS specifically for the Lively Wallpaper app. This app offers various customization options, which are stored in the LivelyProperties.json file along with input types such as sliders and text boxes. To ...

EJS include function not working properly

In most cases, my EJS pages include the code below: <%- include('elements/fbviewpagepixel.ejs') %> Everything runs smoothly except for one particular page where I encountered an error message stating include is not a function. I managed t ...

How do you update the bind value in VueJs when using :value="text"?

My attempts at updating a string when the content is changed inside a textarea are not successful. Vue component: <template> <div> <textarea :value="text" @change="changed = true" @keyup="changed = true"&g ...

The assets path is the directory within the installed package that houses the main application files following the completion of a

I have a Vue.js UI component that is internally built using webpack. This reusable UI component library references its images as shown below: <img src="./assets/logo.png"/> <img src="./assets/edit-icon.svg"/>   <i ...

JavaScript - Capture user input and store it in a cookie when the input field is changed

Any help with my issue would be greatly appreciated. I'm currently working on saving the value of a form input type="text" to a cookie when the input has changed. It seems like I'm close to getting it right, but unfortunately, it's not worki ...

What is the best way to invoke a TypeScript function within a jQuery function?

Is it possible to invoke a TypeScript function within a jQuery function? If so, what is the correct approach? Here is an example of my component.ts file: getCalendar(){ calendarOptions:Object = { height: 'parent', fixedWeekCount : ...

Trouble receiving Ajax response

Below is the code snippet I am working on: function f(){ var value = ""; var request1 = $.ajax({ url : '/a', type: "GET" }); var request2 = $.ajax({ url: '/b', type: ...

Tips for updating property values when calling a TypeScript function

Hello everyone, I am looking to convert a snippet of JavaScript code into TypeScript. JavaScript function newState(name){ var state ={ name : name, age : 0 } return state } function initStates() { this.JamesStat ...

How should the directory be organized for the param with a prefix in Nuxt.js?

My route is set up as /en/rent-:productSlug How should I organize the directory for this route, considering that the parameter productSlug includes the prefix rent? ...

Angular ng-repeat failing to display data as expected

I've been attempting to create a table from a JSON structure, but I'm having trouble getting it to display correctly. The output is not appearing as expected for the first two cells; "Partial" is empty and only filling the last one. You can see ...

Is there a way to enlarge an iFrame to fill the entire screen with just a button click, without using JavaScript

I am currently attempting to achieve full screen mode for an iFrame upon clicking a button, similar to the functionality on this site. On that website, there is a bar that expands to full screen along with the embedded game, which is what I am aiming for. ...

Utilizing a Custom Validator to Compare Two Values in a Dynamic FormArray in Angular 7

Within the "additionalForm" group, there is a formArray named "validations" that dynamically binds values to the validtionsField array. The validtionsField array contains three objects with two values that need to be compared: Min-length and Max-Length. F ...

"Unexpected discrepancy: Bootstrap Glyphicon fails to appear on webpage, however, is visible

I am having some trouble getting the glyphicon to display properly in my side nav. The arrow head should rotate down, which is a pretty standard feature. Here is the link to the page: The glyphicon should be visible on the "Nicky's Folders" top leve ...

There seems to be an issue with the hidden field value not being properly set within the

I created a function called getConvertionValue. Inside this function, I make an ajax call to the getCurrencyConvertion function in the controller. function getConvertionValue(from, to) { if (from != to) { $.ajax({ url: base_url + 'admin/o ...