Undefined return on Collection.get function in backbone.js

I'm encountering an issue with collection.get and model.get methods returning undefined values.

Here is my initialization code:

initialize: function () {
    this.collection = new productsCollection();
    this.model = new productModel();
}

And here is my rendering code:

this.collection.fetch({
    success: function (product) {
        console.log(product);
        $(that.el).html(_.template(productListTemplate, { products: product.models, _: _ }));
    }
});

The list of products displays fine. When I click on each product, a popup appears where the name can be changed.

I want to set a new name in the model and trigger save, but I am unable to get the model of the product. Here is the related code:

$("#productName").val($(e.currentTarget).html());

var ID = $(e.currentTarget).data("id");
var item = this.collection.get(ID);

console.log("start..........");
console.log(item);
console.log(ID)
console.log(this.model.get(item));
console.log("end..........");

$('.modal').modal('toggle');

I can see the correct id in the console, but not the collections and models. Can someone please help me out? Thank you in advance.

UPDATE: Here is the complete view code:

function ($, _, Backbone, popupModal, productTab, productsCollection, productListTemplate, productModel) {
    // View implementation
}

UPDATE: Responses

this.collection

// Output describing the collection

this.model

// Output describing the model attributes

this

// Detailed output of current context

UPDATE: Expanded collection details

// Detailed information about the collection contents

Answer №1

The issue lies in the necessity of binding all functions that will be called by DOM events to the specific instance of your view:

To resolve this, insert the following line into your initialize method:

_.bindAll(this, "submitForm", "toggleMenu", "closeModal")

If not done, this within the function will refer to the global window object rather than the desired instance of your view.

Answer №2

In the scenario where

Collection.findWhere({_id: ID}) // retrieves the correct answer

We can infer that:

  • for Model, the crucial element is idAttribute
  • for Collection, the important factor is modelId

For instance:

var Model = Backbone.Model.extend();
var Col = Backbone.Collection.extend({ model: Model });

var Persons = new Col([{
    _id: 1,
    name: 'Ken'
}, {
    _id: 2,
    name: 'Mike'
}, {
    _id: 3,
    name: 'John'
}]);

console.log( Persons.get(1) ); // returns undefined

If we specify the idAttribute of M:

var M = Backbone.Model.extend({ idAttribute: '_id' });
...
console.log( Persons.get(1) ); // retrieves the model of Ken

There are situations where Model is unnecessary, like:

var Col = Backbone.Collection.extend();

var Persons = new Col([{
    _id: 1,
    name: 'Ken'
}, {
    _id: 2,
    name: 'Mike'
}, {
    _id: 3,
    name: 'John'
}]);

console.log( Persons.get(2) ); // returns undefined

To address this issue, we simply need to redefine the original modelId method:

var Col = Backbone.Collection.extend({
    modelId: function() {
        return '_id';
    }
});
...
console.log( Persons.get(2) ); // retrieves the model of Mike


P.S : Further details available in official documentation.


P.S again: Older versions of BackboneJS do not support modelId

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

Incorporate JSON code seamlessly into an HTML file with D3

I have been experimenting with a Sankey chart using the code available at this link: https://gist.github.com/d3noob/c2637e28b79fb3bfea13 Interestingly, I can view the chart in Firefox, but not in Chrome. I suspect this may be due to Chrome's restrict ...

Is there a way to specifically retrieve the number of likes or followers from Facebook, Twitter, Instagram, and Snapchat in order to display them on my HTML website?

Can you provide guidance on how to obtain the total numbers of likes or followers for our Facebook, Twitter, Instagram, and Snapchat pages without including the plugin boxes or buttons? We are solely interested in the actual numbers. Would this be feasibl ...

FlexiGrid issue: WebMethod failing to execute

I'm encountering an issue with FlexiGrid in my project. The problem lies in the WebMethod not firing properly, specifically during a Json/Ajax call. Despite setting a debug point at the WebMethod and confirming the correct URL through Firebug, it stil ...

Is it possible to minify HTML in PHP without parsing JavaScript and CSS code?

After finding a solution in this discussion, I successfully managed to 'minify' HTML content. function process_content($buffer) { $search = array( '/\>[^\S ]+/s', // eliminate spaces after tags, except for ...

How do I create a specific onShow onHide event in jQuery for a single targeted element?

I have implemented the following code to trigger on-show and on-hide events. This allows for automatic execution of custom functions when a DIV becomes visible, making necessary changes at that moment. (function ($) { $.each(['show', &apo ...

Guide on transferring session-specific information from the server to the client via express APIs

In order to display the username in the chat section of our web application, we are utilizing websockets for real-time communication. However, we are facing an issue where the chat page is rendered as an API response using res.render(). Inside this HTML re ...

Create basic HTML using the react.cloneElement method

When using React.cloneElement(), the first parameter always needs to be a react component that is passed as children in props. Is there a way to pass a simple HTML node as a child? Please see the example code below for clarification: Dialog.jsx (Common c ...

Using Javascript, delete all chosen HTML elements containing innerText

Looking to extract certain HTML tags from a block of code in TextArea1 and display the modified output in TextArea2 upon clicking a button. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8&quo ...

Two interconnected queries with the second query relying on the results of the first

I am currently facing a challenge in my Phonegap (Cordova) application where I need to display a list of items, each requiring an additional query. Let me simplify it with an example scenario. Imagine a student can be enrolled in multiple courses and a co ...

Angular Component - Array missing initial value in @Input property

Having trouble transferring values between components? I'm currently dealing with a situation involving two components: report-form and comment-form. The report form contains an array of comments, displaying a list of comments and a button for each on ...

Generate a hyperlink within a paragraph

Can anyone provide tips on how to turn a string from Json into a paragraph with a hyperlink included? <p>Dumy Dumy Dumy Dumy Dumy Dumy Dumy DumyDumyDumyDumy abc.com </p> Currently, the paragraph displays as is, but I would like to make abc.c ...

What is the best way to save the toggleClass value of various selectors along with their corresponding classes in localStorage?

I've been attempting to preserve the toggled class of multiple elements using local storage or cookies in order to maintain the toggled class after a page refresh. Despite trying various solutions such as js cookie and other tutorials, I've had n ...

Eliminating the data type from the array of JSON entities

In my Node.js project, I have defined a class as follows: let id; let totalCalls; let totalMinutes; class CallVolume { constructor(id){ this.id = id; this.totalCalls = 0; this.totalMinutes = 0; } } module.exports = CallVolume ...

The live() function is causing issues with my ajax request

Within my webpage, I have a link with an onclick() event that should display a div containing a date input text named "datepicker0", followed by another div with the id of "bContent". I've included the script below to implement a date filter on the d ...

Applying CSS rules from an array to elements by looping through

I'm looking for a way to allow users to input CSS styles and have those styles applied to the last selected element, which is determined by the "rangeselector" variable. Currently, the code selects the correct element, but only the first CSS rule is b ...

Caption image on hover

Is it possible to make an image overlap text on a horizontal menu bar when hovering with the mouse? I am designing a horror website and would like a bloody handprint to appear over the links in the menu bar when they are hovered over. I know this can be do ...

PHP is capable of showing echo statements from the function, however it does not directly showcase database information

My current challenge involves using AJAX to pass the ID name of a div as a string in a database query. Despite being able to display a basic text echo from my function, I'm unable to retrieve any content related to the database. // head HTML (AJAX) $( ...

What is the best way to retrieve a comprehensive outcome from a sql search utilizing php and consequently showcase it using javascript?

Need help with my PHP script that executes a query and returns multiple rows? Learn how to use json_encode in conjunction with JavaScript to fetch this data and display it in a table. This code snippet echoes two JSON encoded lines, each representing one ...

Learn how you can swap out UI elements instead of simply appending new ones onto the existing interface. Discover the power of JavaScript, the Fetch API, and Dom

Currently, I am working on a small project to learn more about APIs and how to interact with them effectively. This project involves searching for and displaying characters from a TV show using data obtained from an API. My issue arises when I try to make ...

Tips for refreshing a webpage after returning from a redirected page

After utilizing certain logic, I am able to redirect to a new page. return RedirectToAction("Index"); If I navigate back to the previous page using the browser's back button, I would like for the "old" page to automatically update with default valu ...