The backbone view is having trouble processing the data from this.model.toJSON()

I've been working on a Backbone code implementation to display all modifications before adding data to my model. However, every time I try to add something from my form, my view returns "this.model.toJSON() is not a function" and I can't figure out what's wrong.

This issue occurs within the "userView" render(). Here are my 2 views, model, and collections:

Model:


      var userModel = Backbone.Model.extend({
          defaults: function() {
            return {
              nome: '',
              sobrenome: ''
            };
          }
      });

View:


         var userView = Backbone.View.extend({
            model: new userModel(),
            tagName : 'div',
            initialize: function(){
              this.template = _.template($("#user-template").html());
            },
            render : function() {
               this.$el.html(this.template(this.model.toJSON()));
               return this;
            }
         });

View 2:


        var userViews = Backbone.View.extend({
            model: users,
            el: $("#user-container"),
            initialize: function(){
              this.model.on("add", this.render, this);
            },
            render: function() {
              var self = this;
              self.$el.html("");
              _.each(this.model.toArray(), function(user, i){
                self.$el.append((new userView({model:  userModel })).render().$el);
              });

              return this;
            }
         });

And finally, my collection:


        var userCollections = Backbone.Collection.extend({
          model: userModel
        });

Apologies for any mistakes in my explanation.

Answer №1

Issue arises when you pass an uninitialized model to the view. Replace userModel with user

_.each(this.model.toArray(), function(user, i){
    self.$el.append((new userView({model:  user })).render().$el);
});

Furthermore, you can simplify the code by using:

this.model.each(function(user, i){
    self.$el.append((new userView({model:  user })).render().$el);
});

In my opinion, it's better to name the collection collection rather than model

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

Utilize Javascript to create a function that organizes numbers in ascending order

Is there a way to modify this code so that the flip clock digits appear in ascending order rather than randomly? $( '.count' ).flip( Math.floor( Math.random() * 10 ) ); setInterval(function(){ $( '.count' ).flip( Math.floor( Math.rand ...

A function cannot be used with Random Song Loop

Recently delving into the world of JavaScript, I encountered a peculiar issue. When attempting to execute the following code within a function, nothing displays in the console. Yet, after testing it without the function, the expected strings appear as inte ...

CSS Class ID selection for selectpicker

I have two classes: selectpicker with different IDs: selected_Test_Platforms and selected_SIL_relevant I am trying to assign a preselection from an array called "availableTestPlatforms" to the selected_Test_Platforms. Currently, when I use the selector $( ...

"Triggering CSS changes with the click of a

I am developing a basic calendar application in PHP and I would like to dynamically change the style of the <td> block based on user interactions. Specifically, I want to implement a behavior where once the "menuclick" class is active, the other cl ...

Retrieving a specific time using a JavaScript interface

I am currently implementing a JavaScript control that can be found on this website: My question is, how can I retrieve the selected date from the control in order to pass it to a postback page? I attempted to figure it out myself, but my JavaScript skills ...

Troubleshooting ASP.NET Content Page Error: jQuery Object Expected

Currently working on designing a personal ASP.NET Web page, I have encountered an issue with making a sticky div using jQuery. Despite all my other jQuery functions functioning properly, the sticky div seems to be causing trouble. stickydiv.js $(document ...

The success method for fetching data fails to trigger, instead displaying only a 'parsererror' message, despite the browser actually receiving the data

There are two collections in my code, BlueCollection and RedCollection. BlueCollection works perfectly fine as it loads data from an array stored in a variable. However, RedCollection is encountering some problems while fetching data from a different array ...

Updating Angular model remotely without relying solely on the controller

I am struggling to call the addRectangleMethod method from my Javascript code in order to retrieve server-side information into the Angular datamodel. However, I keep encountering an error stating that the method I'm trying to call is undefined. It&ap ...

Developing desktop applications using C# scripting

I currently have a C# desktop program that is able to work with new C# plugins. My goal is to modify the existing C# application to allow for scripts to be used as plugins. These scripts could be in JavaScript, Windows Script Host (WSh), or any other form ...

Tips for clearing a saved password in a browser using Angular.js and Javascript

There is an issue with the password and username fields in my Angular.js login page. When a user clicks on the 'remember me' option in their browser after logging in, the saved username and password are automatically displayed in the respective f ...

Troubleshooting problems with AngularJS placeholders on Internet Explorer 9

On my partial page, I've included a placeholder like this: <input name="name" type="text" placeholder="Enter name" ng-class="{'error':form.name.$invalid}" ng-model="Name" required /> I have also set up client side validation for the ...

Creating a personalized aggregation function in a MySQL query

Presenting the data in tabular format: id | module_id | rating 1 | 421 | 3 2 | 421 | 5 3. | 5321 | 4 4 | 5321 | 5 5 | 5321 | 4 6 | 641 | 2 7 | ...

Unraveling the Power of Recursive Functions within a React.JS

I'm encountering an issue with a React project. It involves a tic tac toe game where I'm currently working on the implementation of the computer player. The problem arises when the human player clicks on one square (Field-component), triggering ...

Click on the link to see the jQuery effect in action

I'm trying to achieve a fade-out effect on the current page followed by fading in a new one. The fade-in effect is working fine, but when I click on the link, the new page loads without first fading out the existing content. The div that I want to app ...

Having trouble resolving "react-native-screens" from "node_modules eact-navigation-stacklibmoduleviewsStackViewStackViewCard.js"? Here's how to fix it

Here is the command I used for setting up react app routes: npm i react-native-router-flux --save After restarting npm with "npm start," I encountered this error message: Unable to resolve "react-native-screens" from "node_modules\react-navigation- ...

Writing and altering content within the <code> element in Chrome is unreliable

Utilizing a WYSIWYG Editor with contenteditable functionality allows users to input "code snippets" using a <code> element. Here is an example: <div contenteditable="true"> <p> This is a paragraph with an <code>inline s ...

Switching between Login Form and Register Form in VueJS template

Recently, I attempted to switch between the 'Login Form' and 'Register Form' using code that I found on codepen Flat HTML5/CSS3 Login Form. While the code functioned properly on its own, when integrated into a Vue Template, the form fai ...

hold on for the arrays to be populated with data from the ajax calls

Currently, I am facing an issue on my page where I need to wait for all data to be loaded and stored in the appropriate arrays before proceeding with any actions. The data retrieval involves three separate AJAX calls, but sometimes the loading process take ...

Stop users from being able to select or highlight text within a content editable div

Is there a method to develop a content-editable div where users are unable to select or highlight content, but can still input information? I'm interested in creating an interface that forces users to delete and enter data character by character, with ...

Validator alert for AMP scripts

I have implemented the amp version for my content management system. Since each article has a different body, some include amp-instagram while others include amp-facebook, and so on. In order to cover all bases, I have added both amp-facebook and amp-inst ...