Revamping the Backbone collection by resetting and parsing data

In my Backbone application, I have a view that renders when a collection is reset. I am fetching data from the server and resetting the collection with this fetched data. However, I'm facing an issue where the values I retrieve from the server are showing up as null in the view.

initialize: function(options) {
    this.options = options;

    this.model.get('projects').fetch({
        data: { 
            organisation_id: this.model.get('id')
        }
    }, {reset:true});

    this.model.get('projects').on('reset', this.render, this);
    this.model.get('projects').on('add', this.addNewProject, this);
    this.model.get('projects').on('sort', this.addProjects, this);
},

render: function() {

        console.log(this.model.get('projects').state);

        this.$el.html( this.template({
            is_owner: this.options.is_owner,
            className: this.options.className,
            pagination: this.model.get('projects').state
        }));

        this.addProjects();

        this.filter = new Pops.Views.OrganisationProjectsFilter({
            el:this.$el.find('.div-organisation-filter-wrapper'),
            model : this.model,
            collection: this.collection
        });

        this.filter.render().el;

        return this;
    },

I've defined a PaginatedProjects collection for handling paginated data. This collection fetches data from the server and initializes pagination states. Despite successfully parsing the data in the collection, when I try to access these values in my view, they seem to be null.

App.Collections.PaginatedProjects= 

Backbone.PageableCollection.extend({

        url: App.API_ROOT + "/projects/paginated",

        // Initial pagination states
        state: {
          pageSize: 2,
          sortKey: "name",
          order: 1,
          totalRecords:null
        },

        // You can remap the query parameters from `state` keys from
        // the default to those your server supports
        queryParams: {
          totalPages: null,
          totalRecords: null,
          sortKey: "sort",
        },

        // get the state from Github's search API result
        parseState: function (resp, queryParams, state, options) {
            this.state.totalRecords = resp.total;
            this.state.totalPages = resp.total / this.state.pageSize;
            this.state.lastPage = this.state.totalPages;
        },

        // get the actual records
        parseRecords: function (resp, options) {
          return resp.data;
        }
});

After running the parse functions on the collection, I see the correct values when I log them. However, these values appear as null when I try to use them in my view. Am I incorrectly using parse or reset functions, or perhaps both?

Answer №1

One possible reason for this issue could be that the data is not arriving in time for rendering. You can try adjusting your code like this:

this.model.get('projects').fetch({
    success: function(model,response) {
        var data = //your solution here

    }   

});

Answer №2

As far as I can tell, you executed a

console.log(this.model.get('projects').state);

and confirmed that it printed correctly. However, when you tried to use it in the following code:

this.template({
        is_owner: this.options.is_owner,
        className: this.options.className,
        pagination: this.model.get('projects').state
    })

it did not display? In my opinion, the issue may not lie with the Backbone Collection itself but could be related to how you are accessing the data in your template. If you are using handlebars and the "state" variable is in json format,

you might have used

{{pagination.pageSize}}

to output it in the hbs file. I vaguely recall that this was not supported previously. You could try using

{{pagination/pageSize}}

Additionally, if this block of code is within an {{#if}} or {{#each}} statement, according to the handlebars documentation, you might need to adjust the scope using

{{../pagination/pageSize}} or {{../../pagination/pageSize}}

I encountered a similar issue some time ago and conducted extensive research to resolve it. Hopefully, this information proves helpful.

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

Pass the value of the search input to child components in Angular 2

Within my Angular 2 application, I am faced with the task of sending the value from an HTML search input to 3 child components only when the user pauses typing for 300ms and has entered a different value than what was previously in the input field. After r ...

What steps should I take to avoid the second eye symbol appearing?

Initially, my signup form had some existing code that included an eye svg to adjust the text obstruction in the password input box. However, after implementing new logic, I noticed a strange occurrence - a black eye logo similar to the Windows one appear ...

Troubleshooting Block-scoped errors on Heroku using Node.js and Express

Currently, I am working with node.js and express on the Heroku platform. While working on the route file, I encountered an issue when using the let keyword. The error message displayed was: SyntaxError: Block-scoped declarations (let, const, function, cla ...

Struggling to implement a sidebar in HTML using jQuery and running into issues?

I am struggling to create a template that includes a navbar, sidebar, and other elements that can be used across multiple HTML files. Despite trying different approaches, including changing the jQuery version and downloading jQuery, I am unable to make it ...

What causes the [$parse:syntax] error when I tap on the arrow icon within Google Maps?

.controller('MapCtrl', [ '$scope', '$http', '$location', '$window', function ($scope, $http, $location, $window) { $http.get('****').success(function (data, dealers, response) { ...

Extracting the month and year from a datetime string: A simple guide

I am working with a JSON object that includes a field called Month with a string datetime value- { Month : "31-Jan-2022 12:00 AM (EST)" .... .... } Is there a way to extract the Month Name and Year from this string using JavaScript's dat ...

Tips on rotating a 3D shape using axis in three.js

Help needed with rotation in three.js I am facing a challenge when trying to rotate a 3D cube in one of my games. //initialize geometry = new THREE.CubeGeometry grid, grid, grid material = new THREE.MeshLambertMaterial {color:0xFFFFFF * Math.random(), sha ...

How to shift an image to the right side of the navbar

Is it possible to change the position of an image within a navbar from left to right? I have tried using the float property but it doesn't seem to work. .logo-img{ float: right; margin: 0px 15px 15px 0px; } <a class="navbar-brand logo-img" ...

What is the process for showcasing a local notification within my application?

Here is the code snippet I am working with: import { LocalNotifications } from '@ionic-native/local-notifications'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scs ...

How can a producer know when it's time to send a message in NodeJS using ZeroMQ?

After conducting some research on patterns supported by zeromq, I have encountered an issue with the PUB/SUB pattern in my recent project as well as the PUSH/PULL pattern. I am using NodeJS for the zeromq implementation. In my examples (server.js & client ...

After the ajax function has finished executing, establish a socket.io connection

Within my application, the initial step involves the client calling a webservice from a nodejs server to fetch historical data from a mongoDB database for visualization using the highcharts library. Subsequently, I need to receive live updates from the ser ...

Are memory leaks a common issue with Angular directives?

Using a simple html file to replicate a memory leak: <!doctype html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.min.js"></script> <script> va ...

Updating the display text length on vue-moment

Currently, I am attempting to showcase an array of numbers const days = [1, 7, 14, 30, 60] in a more human-readable format using vue-moment Everything is functioning correctly {{ days | duration('humanize') }} // 'a day' // '7 d ...

Navigational bar with React and Next.js. Issue: Hydration unsuccessful due to inconsistencies between the initial UI and the server-rendered content

I am working on a project with Next.js and React. I've created a navbar component but I keep encountering the following error message multiple times: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warni ...

Recursive sorting and parsing of JSON data with multiple levels

I'm new to using recursion in JavaScript and need some guidance to understand it better. I have a JSON data structure with multiple levels of nested "subcategories". const STORE_CATEGORIES = [{ "Id":"1", "Name":"One Parent", ...

Utilizing the summernote editor in combination with vue.js 2

Integrating Summernote into a Vue.js 2 single-page application has been quite a challenge for me. Not all my pages require the Summernote editor, so I decided to turn it into a component by creating an export function in my Vue file. export default { ...

What is the best way to limit the date picker to only accept numbers and hyphens in the input field while blocking any other input in Vue?

I have been utilizing the vue2-datepicker npm package for handling dates. The date input currently accepts all alphabets, numbers, and special characters but I only want it to allow numbers, hyphens, and forward slashes. It's simple to achieve this us ...

Is there a way to determine if an app is installed on a phone using Javascript within Safari on iOS 9 or later?

Prior to iOS 9, one method of determining whether an app was installed on an iPhone using javascript involved utilizing a custom URI scheme followed by a timeout: window.location = "yourapp://"; setTimeout(function() { window.location = "h ...

Concealing a DisplayFor component with the help of Jquery

Hey there, I currently have a 'td' element that appears like this <td style="font-weight:bold"> @Html.DisplayFor(x => x.Parts[i].QtyInItem, new { htmlAttributes = new { @class = "qtyInItem" } }) </td> A ...

Exclude mock files from webpack configuration in AngularClass/angular2-webpack-starter for production builds

I've encountered some obstacles while working with the AngularClass/angular2-webpack-starter framework, specifically in configuring its webpack settings. My goal is straightforward, yet I've been struggling to achieve it. In my project directory ...