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

How can you assign a strokeStyle color to a Canvas using a CSS property?

Our team is currently working on an Angular2 / Ionic 2 project where we have implemented a HTML Canvas element that allows users to draw on it. One challenge we are facing is how to set the Canvas strokeStyle property using a color provided by a CSS style. ...

Is it necessary for the error event of xmlhttprequest to include an error message?

Currently, I am in the process of developing an AJAX request within a Firefox extension. The following code snippet illustrates my approach: function GetMenu(){ var oReq = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(); ...

Troubleshooting issue: Angular not resolving controller dependency in nested route when used with requirejs

When the routes are multiple levels, such as http://www.example.com/profile/view, the RequireJS is failing to resolve dependencies properly. However, if the route is just http://www.example.com/view, the controller dependency is resolved correctly. Below ...

Are Bootstrap Input groups inconsistent?

Hey there! I've been working on the sign-in example, but I seem to have hit a roadblock. In my local setup, the top image is what I see in my browser after running the code, while the desired layout that I found on the Bootstrap site is the one below ...

Should all pages in React be rendered on the server side?

Currently, I rely on Next.js for implementing server-side rendering on my React website. At the moment, I have implemented server-side rendering across almost all pages of the site, including profile information and other content that requires a login to ...

Run module following a POST request

I am currently working on integrating real-time information transmission through sockets using socket.io, along with push notifications sent via the OneSignal platform. However, I have encountered an issue where placing both functionalities in the same mo ...

Tips for incorporating a visible marker beside the dropdown arrow

When developing my React application with React hooks forms, I have a select component where I need to include a clear indicator 'x' icon next to the dropdown icon. The current select component code is: <Form.Control size="sm" as=&q ...

Unable to retrieve the value from a textarea when using Shopify Product Options by Bold

I'm currently facing an issue trying to retrieve the value of a textarea using Shopify's Product Options by Bold. The code works fine locally, but when I transfer it over to Shopify, I am unable to get the value. Despite looking at various resour ...

Automatically insert content into a div following the execution of an AJAX delete function using jQuery

I've been working on a feature to display an auto-populated message in the results div when a user deletes the last item from their favorites list, indicating that it is empty. However, I've hit a roadblock and can't seem to make it work. H ...

Utilizing Async / Await in the created lifecycle hook - Vue2

I recently installed the vue-element-loading package and added its component to my page.vue: <vue-element-loading :active="isActive" :is-full-screen="true"/> After adding a variable to my data: data () { return { isActive: false, } } I th ...

Arrange elements in a vertical flow based on the height of the container

I am attempting to alter the direction of Elements to be vertical. Here is an example: By default, HTML elements are displayed horizontally like this:- #container { position: absolute; width: 400px; height: 200px; border: 1px solid gree ...

The text content is not in alignment with the server-rendered HTML for translation purposes with i18n

I have successfully implemented i18n in my Next.js project. The folder structure for my locales is as follows: public/locales/en/translation.json and public/locales/fr/translation.json The error I am encountering is: Uncaught Error: Text content does n ...

Spinning image on button click with seamless animation in Javascript

I'm trying to make an image rotate every second using the code below, but it's not working. Can you help me figure out why? <html> <head> <style> .rotated-image { -webkit-transform: rotate(2deg); transform: rotate(2deg); } & ...

Retrieve information from various MongoDB collections

Greetings! I currently have a database with the following collections: db={ "category": [ { "_id": 1, "item": "Cat A", }, { "_id": 2, "item": "Cat B" ...

Unable to display the popup modal dialog on my Rails application

I currently have two models, Post and Comment. A Post has many Comments and a Comment belongs to a Post. Everything is functioning properly with the creation of posts and comments for those posts. Now, I have a new requirement where when clicking on "crea ...

Having difficulty grasping the concept of toggleClass and jQuery selectors

I am struggling to understand the getLiveSearchUsers function in my JS file. Could someone please help me? I don't quite grasp what selector[0] is and what toggleClass is doing here. $.post("includes/handlers/ajax_search.php", {query:value, userLogge ...

Customize the HTML tags in the Froala text editor with easy insertion and removal

In my AngularJS project, I am utilizing Froala editor. I want to create a unique functionality where a custom button wraps selected text with <close></close> tags when activated. Moreover, if the selected text is already wrapped with these tags ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

Ways to verify the occurrence of a successful event following the execution of a save() operation on a model

Below is the snippet of code I am using to store extra properties in a model (specifically, the answer model) selectMedia: => # Post media to server @options.answer.id = @options.answer.get('_id') @options.answer.url = "/v1/answers/#{@o ...

What is the best way to modify the size of a canvas element while maintaining effectiveness?

I've encountered an issue while using Canvas to create a pie chart with chart.js. Despite adjusting the dimensions of the canvas element, it continues to take up the entire page. <canvas id="myChart" height ="200" width="200"></can ...