Backbone "recalling" stored data in attributes

Presented here is a basic model:

myTestModel = Backbone.Model.extend({
    defaults: {
        title: 'My Title',
        config: {},
        active: 1,
    }
})

While nothing particularly stands out, there is an interesting observation regarding the persistence of values in the config option between instances. To illustrate this:

var test1 = new myTestModel();
test1.set('title', 'A New Title');
test1.get('config').screen_name = 'Joe';
alert( test1.get('title') );               // 'A New Title', as expected.
alert( test1.get('config').screen_name );  // 'Joe', as expected.

var test2 = new myTestModel();
alert( test2.get('title') );               // 'My Title', as expected.
alert( test2.get('config').screen_name );  // 'Joe', NOT as expected.

The concern that arises is why in test2, the value of screen_name from test1 is maintained. The question then becomes, how can this unintended behavior be prevented?

Answer №1

Uncover a common pitfall in Javascript, as explained in the documentation for model.defaults:

Keep in mind that in JavaScript, objects are passed by reference. So, if you use an object as a default value, it will be shared across all instances. It's better to define defaults using a function.

You can switch to using a function instead of an object to define your defaults:

myTestModel = Backbone.Model.extend({
    defaults: function () {
        return {
            title: 'My Title',
            config: {},
            active: 1
        };
    }
});

Check out this demo at http://jsfiddle.net/nikoshr/Y7PYj/

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

React virtual list module: Scrolling down through code commands

In my React Grid with Virtual Scrolling, I am facing a challenge with the lack of a "scroll to row feature." At times, I need to select a specific row programmatically and ensure that it is displayed to the user. Although I have the ID of the desired row ...

Converting Promises to Observables

Struggling with the syntax as I delve into learning Angular, I need to transform a promise into an Observable. Let me share what I've encountered: In the function getCountries (subscribed by another utility), there is a call required to fetch a list ...

How can I organize data from A to Z in alphabetical order in React Native when the user chooses the A to Z option from the dropdown menu?

I am working on a screen that can display up to 1000 data retrieved from the API. Here is the image: Now, I have implemented a drop-down box where users can select alphabetically from A to Z. After selecting an alphabetical order, the data will be arrang ...

Utilizing Electron to save editable user data in a .txt file

I am making an electron app that converts data from .txt files to Javascript arrays. This data is stored inside a folder called faces in the main directory. I also have a button in my app which, when clicked opens file explorer at the faces folder so the u ...

Transforming a detailed JSON structure into a more simplified format with Angular 2

As a newcomer to Angular 2, I find myself encountering a hurdle in filtering unnecessary data from a JSON object that is retrieved from a REST API. Below is an example of the JSON data I am working with: { "refDataId":{ "rdk":1, "refDataTy ...

Is it possible for two components to send two distinct props to a single component in a React application?

I recently encountered a scenario where I needed to pass a variable value to a Component that already has props for a different purpose. The challenge here is, can two separate components send different props to the same component? Alternatively, is it po ...

Upon selecting the correct prompt, it fails to respond when I press enter

I attempted to use a multi-search script that I found on a website. I followed the instructions given and made the necessary changes. After saving the file as an HTML document, I opened it in Chrome. However, when I type in a word and hit enter, nothing ha ...

What is the method for linking events across multiple objects?

When a user clicks on the confirmation button in a Twitter Bootstrap modal window, I trigger a deletion action on the page. The modal contains two buttons - one for canceling the action and another for confirming it. Once the user confirms the delete act ...

Exporting Axios.create in Typescript can be accomplished by following a few simple

My code was initially working fine: export default axios.create({ baseURL: 'sample', headers: { 'Content-Type': 'application/json', }, transformRequest: [ (data) => { return JSON.stringify(data); } ...

Strategies for temporarily storing values within md-list-item in AngularJS

I am attempting to populate a list with items using material icons. The issue is that the values are being added permanently when the material icon is clicked, disregarding the save and discard buttons at the bottom of the card. My goal is to add values te ...

Enable autocomplete feature in a PHP form once the user starts typing their name

After searching for similar questions, I couldn't find any with the same "variables," so here's my dilemma: I have a basic form where I input a name and I want the rest of the form to be filled in automatically (ID). Retrieving data from the da ...

What is the best way to calculate the total duration (hh:mm) of all TR elements using jQuery?

I currently have 3 input fields. The first input field contains the start time, the second input field contains the end time, and the third input field contains the duration between the start and end times in HH:mm format. My goal is to sum up all the dur ...

Transferring information between an ASP web form page and an Angular2 application

Currently, I am working on a project that involves dealing with a legacy WebForms system. The system is gradually being updated to Angular 2, but the transition is happening incrementally. In order to effectively integrate information from the legacy sect ...

"Error message: Antd datepicker is throwing an error stating that date.clone/date.load is not a

I am working on a React app that has a checkbox to disable a datepicker. However, when I use the checkbox to disable it, I am unable to select any date. If I remove the checkbox and its function, there is no error. Currently, the error message I am getting ...

Is the variable leaping to a superior scope?

A few days back, I encountered a strange bug in my code that has left me puzzled. It appears that a variable declared within a narrower scope is somehow leaking into a broader one. Any insights into what might be going wrong here? Here's a simplified ...

What is the process of adding a div to the left side of the parent element in AngularJS

I am trying to append the code on the left side of the click. My current controller code looks like this: demo.$inject = ['$scope']; demo.directive("boxCreator", function($compile){ return{ restrict: 'A', l ...

Transitions in Vue do not function properly when used in conjunction with a router-view containing a

Recently, I developed a component where I implemented router-view exclusively to facilitate route-based changes. It's worth mentioning that this is the second instance of router-view, with the first one residing in the App.vue component. Interestingly ...

Bootstrap - Keeping track of the collapse state of <div> elements after page refresh

Looking for some guidance as a javascript/jquery beginner - I am utilizing Bootstrap along with data-toggle and collapse classes to display or hide divs. I have been searching online trying to find a solution that will maintain the state of all divs, wheth ...

Alternative way to search for child elements within an element without the use of jQuery

I am in the process of creating a universal set of functions to verify the existence of children with specific attributes within a particular element. Unfortunately, I do not have access to jQuery for this task. Here is an example function call: has_chil ...

Using the Unleash Feature server in a browser for React projects: A step-by-step guide

I'm currently working on implementing the unleash feature toggle in my React Project. Everything is running smoothly with the backend server (thanks to the Java SDK), but I've hit a roadblock when it comes to making unleash requests from the brow ...