Is my implementation of Model and Views in backbone.js accurate?

I'm new to backbone.js and I've just created my first page. I'm curious to know if I'm headed in the right direction with my approach (if there even is a "correct" way in software development).

Is there a way to automatically bind model properties (attributes) to HTML elements?

The HTML structure:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>settings page</title>
    <link rel="stylesheet" type="text/css" href="../Content/theme.css" />
    <script language="javascript" src="../Scripts/jquery-1.7.1.js"></script>
    <script language="javascript" src="../Scripts/underscore.js"></script>
    <script language="javascript" src="../Scripts/backbone.js"></script>
    <script language="javascript" src="../Scripts/settings.js"></script>
</head>
<body>
    <div style="width:95%;margin:10px;padding:10px;background-color:#ffffff;color:#000000;padding-bottom:8px;padding-right:5px;padding-top:4px;float:left;">
        <h1>
            Settings...
        </h1>  
        Server URL (cloud based API):      
        <br />
        <input id="settings-service-url" type="text" size="100" />
        <br />
        <br />
        Timeout:      
        <br />
        <input id="settings-timeout" type="text" size="100" />
        <br />
        <br />
        <button id="update-settings">Update Settings</button>
    </div>    
</body>
</html>

Javascript code:

$(document).ready(function () {

    if (typeof console == "undefined") {
        window.console = { log: function () { } };
    }

    Settings = Backbone.Model.extend({
        defaults: {
            ServiceUrl: "",
            Timeout: 0
        },

        url: function () {
            return '/settings';
        },

        replaceServiceUrlAttr: function (url) {
            this.set({ WisdomServiceUrl: url });
        },

        replaceTimeoutAttr: function (timeout) {
            this.set({ Timeout: timeout });
        }

    });

    SettingsView = Backbone.View.extend({

        tagName: 'li',

        events: {
            'click #update-settings': 'updateSettings'
        },

        initialize: function () {
            _.bindAll(this, 'render');
            this.settings = new Settings;
            this.settings.fetch({ success: function () {
                view.render(view.settings);
            }
            });

        },

        updateSettings: function () {
            view.settings.replaceServiceUrlAttr($('#settings-service-url').val());
            view.settings.replaceTimeoutAttr($('#settings-timeout').val());
            view.settings.save();
        },

        render: function (model) {
            $('#settings-wisdom-service-url').val(model.get("WisdomServiceUrl"));
            $('#settings-timeout').val(model.get("Timeout"));
        }
    });

    var view = new SettingsView({ el: 'body' });

});

Answer №1

Your view contains a mistake that needs to be addressed. One common practice is to pass the model as a parameter when creating a new view instance, like this:

var newView = new SettingsView({ "el": "body", "model": new Settings() });

This allows you to access the model using this.model within your view.

Another issue is with the variable name view in your code. With Backbone's View, you can have multiple instances of the same View class. For example:

var view = new SettingsView({ "el": "body", "model": new Settings() });
var secondView = new SettingsView({ "el": "body", "model": new Settings() });

If you then call view.settings.save();, it will always refer to the method in the first view instance because of the variable name "view". Instead, use this to reference the current instance:

In addition, calling both settings methods in your model seems unnecessary as they only call set. Consider calling set directly on the model.

Lastly, using tagName: 'li' and inserting an element may not work as expected. The tagName attribute only has an effect if no element is inserted into the constructor. Otherwise, the view's element will be the one passed into the constructor.

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

The required element was not discovered

Whenever I attempt to execute npm run serve, it reaches 98% completion and then halts, displaying the following error message: An issue occurred while compiling with a total of 1 error: ...

Send a request to the uClassify API using the Node request module

I'm currently working on integrating the uClassify API into my Node project, but I'm encountering some issues with my code. Here's what I have so far: const req = JSON.stringify('Hello, my love!'); const options = { body: ...

Modify the contents of an array within a string using JavaScript

let message = "hello https://ggogle.com parul https://yahoo.com and http://web.com"; let url = ["https://ggogle.com", "https://yahoo.com", "http://web.com"]; I'm trying to replace all URLs in the 'message' array with "***" from the 'ur ...

Utilizing the power of Node.js with Oracle seamlessly, without the need for the Oracle Instant

Currently, I am working on testing the connectivity to our Oracle databases. Recently, I came across node-oracledb, a tool released by Oracle that aims to simplify this process. However, one major hurdle is the requirement of having the Oracle Instant Clie ...

Issues with nested array filtering in JS/Angular causing unexpected outcomes

I am faced with a particular scenario where I need to make three HTTP requests to a REST API. Once the data is loaded, I have to perform post-processing on the client side. Here's what I have: An array of "brands" An array of "materials" An array o ...

React - Uncaught Error: e.preventDefault is not a function due to Type Error

Encountering an issue with Axios post and react-hook-form: Unhandled Rejection (TypeError): e.preventDefault is not a function The error arises after adding onSubmit={handleSubmit(handleSubmitAxios)} to my <form>. Seeking to utilize react-hook-form ...

What strategies can I use to ensure that I can successfully send 3,000 requests to the Google Drive API using node.js without surpassing

I'm currently assisting a friend with a unique project he has in mind. He is looking to create 3000 folders on Google Drive, each paired with a QR code linking to its URL. The plan is to populate each folder with photos taken by event attendees, who ...

Having trouble setting up node-gyp on ubuntu

npm http 200 https://registry.npmjs.org/weak/-/weak-0.2.2.tgz npm http GET https://registry.npmjs.org/bindings npm http 304 https://registry.npmjs.org/bindings > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8dfcdc9c3e898 ...

Is there a method to directly download large files from the server without having to wait for the blob response?

I'm currently working on video file requests using axios. I have set the requests with responseType: blob to create a video player once the response is received with window.URL.createObjectUrl(). However, I also have a button that allows the user to d ...

Control and manage AJAX POST requests in the controller

I'm currently working on implementing an ajax post request feature in my project. The goal is to have a button on my html page trigger a javascript event listener, which then initiates an ajax post request to receive some text data. However, I seem to ...

Unable to display information retrieved from an API within a React application

I am facing an issue with rendering questions fetched from an API. I have set up the state and used useEffect to make the API call. However, when I try to display the questions, it seems to disrupt my CSS and show a blank page. I even attempted moving the ...

Unable to make a div grow within a Popper component in a React.js application

I'm facing a challenge with implementing a CSS feature and need some assistance. https://i.stack.imgur.com/KXpGd.png Upon clicking the "See link options" button, the content loads but spills out of the popper. My goal is to have the popper expand in ...

There was an issue with the NextJS axios request as it returned a status code

I'm currently in the process of developing an application with NextJS and Strapi In my project, I am fetching data from Strapi using Axios within NextJS Next: 14.0.4 Axios: ^1.6.5 Strapi: 4.17.1 Node: 18.17.0 Here is the code snippet: import axios f ...

Ways to incorporate a scroll feature and display an iframe using JQuery

Is there a way to animate the appearance of hidden iframes one by one as the user scrolls down the website using jQuery? I have come across some solutions, but they all seem to make them appear all at once. I'm looking for a way to make the iframes s ...

Trouble accessing setState within an axios call in ReactJs

I've encountered an issue while attempting to set the state of the variable isCorrectAnswer within an axios call. The error message Cannot read properties of undefined (reading 'setState') is showing up in the console log. What mistake am I ...

Display the full price when no discount is available, but only reveal the discounted price when Vue.js is present

In my collection of objects, each item is structured like this: orders : [ { id: 1, image: require("./assets/imgs/product1.png"), originalPrice: 40, discountPrice: "", buyBtn: require(&q ...

Extracting Unprocessed Data with Node.js Express

I am currently working with an Express server that handles a login form page: const app = express(); // part A app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded()); app.get('/login', ...

Obtain the initial Firebase child element without a specific key

Trying to access the first child of a firebase object is my current challenge. The reference is structured as follows: var sitesToVisitRef = firebase.database().ref('sitesToVisit') The reference is confirmed functional as I am able to write to ...

What is the best practice for using templates in a constructor versus connectedCallback?

Should I apply template in the constructor or connectedCallback of a custom element? In my experience, when I apply it in connectedCallback, sometimes attributeChangedCallback is called before and I can't query for elements. export class TestElement ...

transferring data from ejs template

In my app.js file, I have an array that stores files. To display these files on a website, I use a for-loop in ejs: <% for(let i = 0;i<posts.length; i++){ %> <li class="listtitle"> <%= posts[i].title %> </li> ...