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

Error encountered upon initializing Node-RED due to the presence of an unexpected token while incorporating the NPM module "file-exists" into the

Currently, I'm in the process of developing an application using Node-RED and I'm looking to incorporate some NPM modules into my project. One particular module from James Thom caught my attention, called node-red-contrib-npm, which automates the ...

Using Styled Components to Implement Background Images in a React Application

I'm currently attempting to pass a background image using a prop, but I'm encountering an issue where it's indicating that url is undefined. const CardImage = styled.div` height: auto; width: 100%; background-size: c ...

PHP implementation for a static header layout

I am interested in learning how to update content without refreshing the header. I have created a simple example below. Header.php <html> <head> </head> <body> <ul> <li><a href="index.php" ...

Stop users from skipping ahead in an HTML5 video

Struggling to stop a user from seeking on the video player. I've attempted to bind to the event, but it's not working as expected. Any suggestions on how to successfully prevent this action? @$('#video').bind("seeking", (e) =& ...

JavaScript regular expressions only recognize certain characters

When submitting a form, I need to validate a field and ensure that only specific characters are allowed. The permitted characters include: a-z A-Z 0-9 % . " ' & - @ # $ * / + = [ ] ! I attempted to use the following regex for validation: var r ...

The issue with the `.load` function in jQuery not functioning properly

I'm currently tackling an issue with a project where I am encountering difficulties with the .load function not working in Google Chrome. Below is the JavaScript code: function link1() { $('#loadarea').html('loading.....' ...

performing functions concurrently within angularjs

I am currently utilizing angularjs 1.0 within my application. There is a dropdown on my cshtml page <select tabindex="2" id="Employee" ng-model="models.SelectedEmployee" ng-change="changeEmployee()" disabled="disabled" class="Answer" size="6"> < ...

Executing Javascript code from a specified web address

Let's say I have an image that needs to be shifted vertically, and I achieve it using the following code snippet: document.getElementById('ImgID1').style.verticalAlign = However, the value by which I need to shift the image is provided thr ...

``It seems like there was an error with WebComponents and NextJS - the hydration failed due to a mismatch between the initial UI and what was rendered on

I'm running into an issue with the following error message: Error: The initial UI doesn't match what was rendered on the server, leading to hydration failure. This problem occurs when I have a NextJS webpage that includes StencilJS web compone ...

A guide on designing a personalized search bar for MUI-Datatables with a sleek outlined style

Check out the default UI from MUI-Datatables v4.3.0 here: https://i.stack.imgur.com/rbHgD.png I want to create a style similar to this: https://i.stack.imgur.com/AUHqC.png Just so you know, I am using the following packages: "@mui/material": &q ...

What is the best way to retrieve the chosen option when clicking or changing using jQuery?

CSS <form name='category_filter' action='/jobseek/search_jobs/' method='get'> <select id="id_category" class="" name="category"> <option value="" selected="selected">All</option> <option v ...

How can I minimize the number of polymorphic methods in my MVC design?

Currently, I am tackling a challenge in creating an MVC framework using PHP, even though my primary expertise lies in Java. I am on the lookout for a solution that aligns with OOP principles and is easily adaptable to various programming languages. Within ...

I seem to be having trouble using my markers on my istamap

function initialize() { var mapProp = { center:new google.maps.LatLng(51.508742,-0.120850), zoom:5, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap"),mapProp); var marker = new ...

A step-by-step guide to incorporating VeeValidate with vue-i18n

When a click event is triggered, I am able to change the language in vue-i18n. However, I am facing an issue with changing the vee-validate dictionary to match the same language. Main.js import VeeValidate from 'vee-validate' import validations ...

Tips for positioning a div element within the body of a webpage to maintain a predetermined height and width

Currently, I am developing a single-page application using AngularJS. I have specific routes in mind where I want to introduce new HTML templates. To accomplish this, I have created a container labeled with the ID #main positioned between two navbars (he ...

managing the reloading of pages and navigating back and forth in the browser

In my project, I am using react and next.js to make API requests from a search bar and display a list of movies on the homepage. Each search result redirects me to a different page that shows detailed data related to the selected movie. However, the issue ...

Vue Websockets twofold

I am experiencing some issues with Laravel/Echo websockets and Vue.js integration. I have set up everything as required, and it works, but not quite as expected. The problem arises when I refresh the page and send a request - it displays fine. However, if ...

"Unraveling the mysteries of deserializing JSON with unfamiliar

Perhaps this may not be achievable. Check out the functioning code below: HttpResponseMessage playerResponse = await client.GetAsync("2018/export?TYPE=players&DETAILS=1&SINCE=&PLAYERS=9988%2C13604&JSON=1"); if (playerResponse.IsSuccessSta ...

Error: Unable to assign a value to the statusCode property because it

During the development of my application backend, I encountered an error while working on the user login route. When testing the route using Postman, I received the following error message: UnhandledPromiseRejectionWarning: TypeError: Cannot set propert ...

NavigAuth - NativeScript Vue's Innovative Authentication-driven Navigation

After spending hours trying to figure this out, I need to ask for help. How can I create a simple Auth-based Navigation within my App? I have successfully set up a Firebase auth user inside my Vuex using an auth listener. Now, all I want is to display th ...