Revise my perspective on a modification in the backbone model

I am new to using Backbone and I am currently practicing by creating a blog using a JSON file that contains the necessary data. Everything seems to be working, although I know it might not be the best practice most of the time. However, there is one specific thing I would like to add - updating my view whenever my model changes. I believe I need to implement some sort of listener for this purpose, but I have tried various approaches found on Stack Overflow without success.

Below is the code I have:

Item (The Backbone Model)

var Item = Backbone.Model.extend({
    defaults: {
        title: 'No Title Provided',
        url_title: 'unique key for URL',
        img_path: 'no image added',
        comment: 'No comments provided',
        category: 'No category specified',
        rating: 0,
        article: 'No article content available'
    },
});

ItemCollection (The Backbone Collection)

var ItemCollection = Backbone.Collection.extend({
    model: Item,
    comparator: function(model) {
        if (sortid == "rating") {
            return -model.get(sortid); // sorts descending
        } else {
            return model.get(sortid); // sorts ascending
        }
    }
});

ItemShelfView (The Backbone View)

var ItemShelfView = Backbone.View.extend({
    className: 'itemshelf',
    tagName: 'div',

    render: function() {
        var self = this;

        // iterate through each item in the collection
        // and add it to the DOM
        this.collection.each(function(item) {

            var itemEl = $('<div />', {
                class: "item well well-lg col-md-5"
            });
            var itemTitle = $('<h3 />').text(item.get('title')).attr('class', "col-md-12");

            var itemLink = $('<a />').attr('href', '#detail/' + item.get('url_title')).attr('class', "btn btn-default navigate col-md-12").text('View full article');

            var itemImage = $('<img />').attr('src', item.get('img_path')).attr('class', "thumbnail col-md-4");

            var articleText = item.get('article');
            var shortText = jQuery.trim(articleText).substring(0, 200).split(" ").slice(0, -1).join(" ") + "...";

            var itemArticle = $('<p />').text(shortText).attr('class', "col-md-8");
            var itemCategory = $('<span />').text(item.get('category')).attr('class', "col-md-8");
            var itemRating = $('<b class="rating" />').text(item.get('rating')).attr('class', "col-md-8");
            var itemComment = $('<span />').text(item.get('comment')).attr('class', "col-md-8");

            itemEl.append(itemTitle);
            itemEl.append(itemImage);
            itemEl.append(itemArticle);
            itemEl.append(itemLink);
            itemEl.append(itemComment);
            itemEl.append(itemCategory);
            itemEl.append(itemRating);

            self.$el.append(itemEl);
        });
        return this;
    }
});

My AJAX call to retrieve JSON data

$.ajax({
    url: 'api/items.json',
    dataType: 'json',
    success: function(data) {
        console.log(data);

        var items = new ItemCollection(data);
        var shelf = new ItemShelfView({
            collection: items
        });

        $('#app').append(shelf.render().$el);

        window.items = items;
        window.shelf = shelf; // make sure items can be edited
    }
});

Thank you! (I have already extensively searched Stack Overflow for solutions.) Greetings!

Answer №1

To achieve the goal of only re-rendering the view of a single model when that specific model is changed, rather than rendering the entire collection again, you can create separate views for each individual model. Currently, your view is designed for the entire collection.

You should extract the code from your collection.each loop and use it to create a new View for each model instead. This way, each View will be responsible for rendering the elements associated with a single model.

With a dedicated view for each model, you can then set up a listener in the model's view to react to any changes made to that particular model, using

this.model.on('change', this.render, this)
. Here is some pseudocode to illustrate this:

ItemShelfView()
   render:
      this.collection.each( function(m) {(
        var mview = new modelView({model: m}) // create a new modelView for each model
      );}

modelView()
    initialize:
      this.model.on('change', this.render, this); // re-renders the model if it changes
    render:
      // insert the rendering logic here
      //(previously part of the each loop in the collection view)

I suggest checking out this tutorial: . It progresses at a slow pace and aligns well with what you appear to be aiming for—rendering a collection of models while updating individual models as needed.

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

Enhancing OpenAI API Responses with WebSocket Streaming through Express Middleware Integration

  Currently, I am in the process of developing an Express.js application that requires integration of OpenAI's streaming API responses to be transmitted in real-time to a front-end via WebSockets. Even though I have established communication between ...

When I implement JavaScript on my website, my HTML content does not show up

Whenever I try to fetch content from a specific URL using AJAX and a script, my HTML content does not show up. In other words, the table element is not displayed on the page. Instead, I am able to retrieve data from the specified URL and display it in an a ...

Navigating - Utilizing dot-notation to reach the top-level function in Express

If we want to use express in a basic javascript file, all we need to do is add the following two lines of code at the beginning (after installing it through npm): var foo = require('express'); var app = foo(); According to the express API guide ...

Making a REST API call with an ID parameter using Angular

I am currently working on an Angular application that interacts with a REST API. The data fetched from the API is determined based on the customer ID, for example: api/incident?customer_id=7. I am unsure of how to incorporate this into the API URL and serv ...

Utilize NodeJS to dynamically alter the text outputted on an HTML page

For educational purposes, I am designing a website where users can sign in by entering their name on the login page. After signing in, they will be redirected to the home page which displays a personalized welcome message using their name. I have included ...

What could be the reason behind datatables automatically setting the table width when the bServerSide parameter is set to true

After parsing the table data, I noticed that the HTML table is being automatically styled with a width of 1649px (seen in the style attribute). <table id="datatable_user" style="width: 1649px;"> This odd behavior only occurs when the data is source ...

Resizing a webpage to fit within an IFRAME

Having just started learning HTML, CSS, and JavaScript, I am attempting to incorporate a page as a submenu item on my website. Below is the code that I have so far: <!DOCTYPE html> <html> <meta name="viewport" content="width=1024"> ...

Minimizing the gap between icon and label text

I have a React form that I need help with. The issue is that I want to reduce the space between the list icon and the label. Here is the CSS I am using: .form__container { display: flex; flex-wrap: wrap; } .form__container input { color: rgb(115, 0, ...

Unable to alphabetically arrange buttons automatically

I am encountering a challenge with automatically sorting buttons alphabetically on my webpage. I am unable to determine the method for sorting these buttons using jquery or javascript, but my goal is to have them sorted automatically when the page loads. I ...

Transferring Data in Vue.js Components through Props

I've encountered an issue while trying to pass a prop from the main Vue instance to a component. While one of the props is being successfully passed, the second one seems to be causing some trouble. Main Instance var app7 = new Vue({ el: &apos ...

JavaScript Automation Script for QuickTime Screen Recording

Recently, I've been working on a JavaScript Automation script to record my screen on my Mac. However, I encountered an issue with the API when it reaches the line doc.close(). QuickTime would hang indefinitely and eventually my Script Editor would tim ...

Looping through an array of JSON objects in Javascript results in finding instances, however, the process records them

Currently, I am executing a script inside a Pug template. The script commences by fetching an array of JSON objects from MongoDB. I then stringify the array (data) and proceed to loop through it in order to access each individual JSON object (doc). Subsequ ...

React: Updating useState array by removing the first element triggered by an event or timer

I am currently working on a function that populates a useState array containing objects representing cars. These cars appear on the left side of the screen and move across until they are off-screen. My goal is to remove these cars from the state array once ...

What is the best way to retrieve the most recent CMS posts information within a Gatsby-constructed project?

I created a static website using Gatsby and everything was working well. However, I encountered an issue when updating the titles and content of posts in Contentful CMS - the changes were not reflected when I refreshed the website. How can I ensure that ...

Steps to trigger a Bootstrap modal when the user clicks anywhere on the webpage

I need assistance with setting up a Bootstrap dialogue modal to open at the clicked position on a mousedown event when a user interacts with the page. Despite my attempts, the dialogue modal is not opening where it should be. Here's what I've tri ...

Extractor of Json-path containing nodes with periods in their names

I utilize the com.jayway.jsonpath:json-path library for efficiently accessing and modifying nodes. An example of a pattern is using "$.dnode.meta" to manage data on the meta node level within the dnode. An example JSON structure for this is: { "dnode": ...

What are the capabilities of Ajax when it comes to utilizing select controls in J

Is there a way to trigger an ajax call when a select control value is clicked? The onChange event doesn't seem to work for me in this case :( This is what I have tried so far: JAVASCRIPT: <script> function swapContent(cv) { $("#myDiv"). ...

Using indented, multi-line logging in a NodeJS environment can help to

I'm looking for a way to display objects that have been printed with JSON.stringify() in the console, specifically within the context of a Mocha test suite output. While my tests are running, I want the object log lines to be indented further to the ...

When the Json response is returned as a string in a SoapUI script assertion

My response is in JSON format, returned as a string: "[{\"Serial\":5,\"Name\":\"hold\",\"Types\":[{\"Serial\":36,\"Id\":5,\"Data\":true}]}]" In my Script Assertion, I have the followin ...

Learn how to gradually make text disappear and reappear using JavaScript or jQuery

I am a beginner in JavaScript and jQuery, and I am trying to achieve a text fade-out effect. Once the text has completely faded out, I want it to return with the same fade-in effect. I have been exploring if statements and fadeIn effects, but I am strugg ...