Ways to define properties in backbone entities

As I work on my app using backbone, I'm encountering a challenge that might be due to a misunderstanding on my part.

I am trying to set specific attributes like titles while also having default values in place. However, it seems that the custom attributes are not being properly applied. Why could this be?

var DataMapper = {
    Models: {},
    Collections: {},
    Views: {},
    Templates: {}
};

DataMapper.Views.OperatorView = Backbone.View.extend({
    el: "#op-panel",
    operators: [],
    events: {
        "click #concat-op-btn": "addConcatOp"
    },
    addConcatOp: function() {
        var concatOperator = new DataMapper.Models.OpContainerBox({title: "Concat", inputCount: 2, outputCount: 1});
        this.operators.push(concatOperator);
        concatOperator.drawContainer();
    }
});

DataMapper.Models.OpContainerBox = Backbone.Model.extend({
    title: "Operator",
    inputCount: 0,
    outputCount: 0,
    defaults: {
        x: 400,
        y: 40,
        leaves: [],
        height: 20,
        width: 120
    },
    drawContainer: function() {
        console.log(this.title); //outputs "Operator" instead of "Concat"
    }
});
new DataMapper.Views.OperatorView();

Answer №1

In the Backbone framework, model attributes are not equivalent to JavaScript object properties. Attributes are stored within the attributes property and can be manipulated using get and set; whereas properties are directly linked to this and accessed through this.property_name.

For instance:

DataMapper.Models.OpContainerBox = Backbone.Model.extend({
    title: "Operator"
});

In this case, title is considered a property, not an attribute. On the other hand, if you do this:

DataMapper.Models.OpContainerBox.new({
    title: 'Concat'
});

Backbone will assign the title attribute as 'Concat'.

If you modify your console.log statement like so:

console.log(this.title, this.get('title'));

You'll observe both 'Operator' and 'Concat' displayed in the console.

All default values should be placed in the defaults property, and if any of these defaults are mutable, it's advisable to use a function for defaults to avoid unintentional reference sharing:

DataMapper.Models.OpContainerBox = Backbone.Model.extend({
    defaults: function() {
        return {
            title: "Operator",
            inputCount: 0,
            outputCount: 0,
            x: 400,
            y: 40,
            leaves: [],
            height: 20,
            width: 120
        };
    },
    drawContainer: function () {
        console.log(this.get('title'));
    }
});

If a function isn't used for defaults, all instances of OpContainerBox will share the same defaults.leaves array via their prototype.

It's essential to utilize get to retrieve attributes: this.get('title') rather than this.title.

The issue of "reference sharing through the prototype" can also arise with the operators array in the OperatorView, prompting a modification such as:

DataMapper.Views.OperatorView = Backbone.View.extend({
    el: "#op-panel",
    events: {
        "click #concat-op-btn": "addConcatOp"
    },
    initialize: function() {
        this.operators = [ ]; // <---- One distinct array per instance.
    },
    //...
});

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

Encountering an issue with Vue JS axios request and filter: the function this.XX.filter is not operational

I am encountering challenges while trying to implement a basic search feature on a JSON file obtained through an API. Each component works independently: I can successfully retrieve data from the API, perform searches on non-API data, and even search cert ...

Determine the card type based on the card number

My array of card types is structured like this: var cards = new Array(); cards [0] = {name: "VISA", length: "13,16", prefixes: "4", checkdigit: true}; cards [1] = {name: "VISA_DELTA/ELECTRON", length: "16", prefixes: "417500,4917,4913", checkdigit: tr ...

How can you locate the position of a selector within a parent or set using jQuery

Could someone please help me determine the position of the current selector within its parent using jQuery? I need this information in order to effectively use the .insertAfter() and .insertBefore() methods to rearrange elements within their nested structu ...

Managing State with Vuex: Storing Getter Results in the State

I'm encountering an issue with my Vuex.Store: My goal is to retrieve an object (getter.getRecipe) by using two state entries as search criteria (state.array & state.selected) through a getter. Then, I want to store the outcome in my state (state. ...

What is the best way to iterate through multiple iframes?

I need help figuring out how to load one iframe while having the next one in line to be displayed. Is there a way to create a script that cycles through multiple iframes after a certain amount of time? ...

Using data-image as the source for Bootstrap Modal

I am currently working on an image gallery that utilizes the Paver jQuery plugin. The gallery is functional, but I am facing an issue where it displays the same image in the modal instead of showing the respective data-image for each image. My goal is to ...

How can I implement user-specific changes using Flask?

I am a beginner with Flask and I am working on a project where users can sign up, and if the admin clicks a button next to their name, the user's homepage will change. Below is the Flask code snippet: from flask import Flask, redirect, url_for, render ...

What is the best way to manage photos from your phone without having to upload them online?

I'm currently developing an application using AngularJS/Javascript, HTML, and CSS within a cloud-based environment on c9.io. My next task is to create and test an app that can access the phone's photo album, apply filters to images, and I'm ...

When using Next.js getServerSideProps(), cookies are not accessible on the initial render after a redirect, but they become available upon refreshing the page

Within my Next.js application, I am serving cookies from the server-side API like this: res.setHeader('Set-Cookie', AJWT) res.redirect(302, '/') Now, in my index.js file, I am attempting to retrieve the cookie before the page is render ...

What is the best way to ensure a function returning a promise works effectively within a forEach loop?

Are you facing challenges using a function that returns a promise inside a forEach loop due to the asynchronous nature of the function? It seems like the forEach loop completes before the promise can finish fetching or manipulating the data. Below is a co ...

Adding 7 days to a JavaScript date

Can you spot the bug in this script? I noticed that when I set my clock to 29/04/2011, it displays 36/4/2011 in the week input field! The correct date should actually be 6/5/2011 var d = new Date(); var curr_date = d.getDate(); var tomo_date = d.getDate( ...

What could be causing the browser to become unresponsive when making several AJAX requests to the same ASP.NET MVC action at once?

The other day, I posed this query: Why is $.getJSON() causing the browser to block? I initiated six jQuery async ajax requests simultaneously on the same controller action. Each request takes around 10 seconds to complete. Upon tracking and logging re ...

How should you correctly display the outcome of a mathematical function on a data property in a v-for loop in VueJS?

Recently, I've been developing a dice roller using Vue for a game project. The approach involves looping through different types of dice with v-for to create buttons and display the result in an associated div element. However, despite correct console ...

Updating View in Angular 2 ngClass Issue

I'm encountering some challenges with updating my view using ngClass despite the back end updating correctly. Below is my controller: @Component({ selector: 'show-hide-table', template: ' <table> <thead> ...

Immediate family members nearby are not an option. We will have to create the form dynamically

On a previous page, there is a form that allows users to input data and define the number of "Attributes" they want to assign to a device by clicking on a button. Users are prompted to specify a name and type for each attribute. If the user selects "Selec ...

Measuring data entries within JSON array utilizing JavaScript and Postman

A specific component is returning two records: { "value": [ { "ID": 5, "Pupil": 1900031265, "Offer": false, }, { "ID": 8, "Pupil": 1900035302, "Offer": false, "OfferDetail": "" } ] } My task i ...

If the window width is less than the specified value, hide the DIV and replace it with a

I came across a discussion about hiding a div if the screen is narrower than 1024px, and I'm looking to implement something similar based on the quoted code below. Essentially, I want to hide one div (id="krug_wide") if the window width is less than 1 ...

What could be the reason for the electron defaultPath failing to open the specified directory?

Hi, I'm experiencing difficulties opening the directory path (/home/userxyz/Releases/alpha) using electron. This is what I have attempted: I have a similar path on Ubuntu: /home/userxyz/Releases/alpha When trying to access this path with the fo ...

React display

I've been working on a personal project and wanted to include a lottery wheel. I came across the 'lottery-wheel' package on npm, but unfortunately, my attempts to install and render it were unsuccessful. To install the package, I used the f ...

Troubleshooting a LESS compiling issue with my Jade layout in ExpressJS

Implementing LESS compilation on the server side using Express was successful, but I faced an issue with jade not recognizing less in layout. Error message displayed in my terminal: if(err) throw err; ^ Error: ENOENT, open '/Users/li ...