The observable object fails to update the view in Knockout

I'm struggling with this error and need some assistance. I've been working on it for a while, but haven't made any progress. Any help would be greatly appreciated! Thanks!

Error:

VM4705 knockout-debug.js:3326 Uncaught ReferenceError: Unable to process binding "with: function (){return currentCat }"
Message: Unable to process binding "text: function (){return clickCount }"
Message: clickCount is not defined

Desired Outcome:

The objective is for the program to display a list of cat names in the "catNames" div and update the information displayed in the "cat" div with details of the first cat from the "data" observable array. When clicking on different cat names from the list, it should set the value of "currentCat" to the selected cat, consequently updating the information in the "cat" div as well.

Link to JsFiddle

Here's my JavaScript code:

var cats = [
  {name:'cat1', photo: 'https://s20.postimg.org/owgnoq5c9/cat_1.jpg', clicks: 0 },
  {name:'cat2', photo: 'https://s20.postimg.org/f9d5f0ccp/cat_2.jpg', clicks: 0 },
  {name:'cat3', photo: 'https://s20.postimg.org/su3xe4s5l/cat_3.jpg', clicks: 0 },
  {name:'cat4', photo: 'https://s20.postimg.org/xdg5zna15/cat_4.jpg', clicks: 0 },
  {name:'cat5', photo: 'https://s20.postimg.org/78yuqivex/cat_5.jpg', clicks: 0 }
];

function CatRecord(cat){
  var self = this;
  self.catName = ko.observable(cat.name);
  self.imgSrc = ko.observable(cat.photo);
  self.clickCount= ko.observable(cat.clicks);
};


var ViewModel = function(){
    var self = this;
  self.data = ko.observableArray([]);

  // data
  cats.forEach(function(cat){
        self.data.push(new CatRecord(cat));
    }); // -- end of for Each

  // view 
  self.currentCat = ko.observable(self.data()[0]);

  self.setCurrentCat = function(catIndex){
    self.currentCat(self.data()[catIndex]);
  };

  // actions
  self.incrementClicks = function(){
    var clickCount = self.currentCat().clickCount();
    self.currentCat().clickCount(clickCount + 1);   
  };
 };


ko.applyBindings(new ViewModel());

And here's the corresponding HTML:

<body>

    <div id="catNames">
      <ul id="catList" data-bind="foreach: data">
        <li data-bind="text: catName, click:$parents[0].currentCat($index()) "></li>
      </ul>
    </div>

    <div id="cat" data-bind="with: currentCat">
      <h2 id="clicks" data-bind="text: clickCount"></h2>
      <img id="photo" src="" alt="cat photo" data-bind=" click: $parent.incrementClicks,
      attr: {src: imgSrc}">

      <h4 id="name" data-bind="text: catName"></h4>
      <button type="submit">Admin</button>
    </div>

  </body>

Answer №1

The issue lies within the click binding situated inside the foreach loop. It should be set up like this:

<ul id="catList" data-bind="foreach: data">
   <li data-bind="text: catName, click:$parent.setCurrentCat"></li>
 </ul>

When invoking the setCurrentCat function, you only need to pass in the specific cat object that triggered the event, removing the need for the index. This can be achieved as follows:

self.setCurrentCat = function(cat){
  self.currentCat(cat);
};

The exact reason why the error is occurring with the with binding is still unclear.

See updated fiddle

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

Utilizing Bootstrap combobox to easily select values by typing them in

I recently started utilizing the bootstrap combobox plugin on my website. Strangely, I've noticed that when selecting from the options in the dropdown list, choosing NewYork works smoothly. However, if I type "New" and attempt to select "New York" fr ...

"Implementing an AngularJS factory that returns a State object instead of typical JSON data fetched from

I have created two factories and I am calling the first one from the second one in my controller. However, instead of receiving JSON data, I am getting data as $$State. I am new to AngularJS and have tried multiple solutions but have not been able to resol ...

Why does the Angular page not load on the first visit, but loads successfully on subsequent visits and opens without any issues?

I am currently in the process of converting a template to Angular that utilizes HTML, CSS, Bootstrap, JavaScript, and other similar technologies. Within the template, there is a loader function with a GIF animation embedded within it. Interestingly, upon ...

Navigating through the maze of ES6 imports and dealing with the complexities

Currently, I am delving into React and creating my own components. However, the issue of project organization has arisen. Here is the structure of my project: Project_Folder - Components - Form - index.js - form.less - package.js ...

Troubleshooting Port Issue When Deploying Node/Sequelize Application on Heroku

I am in the process of developing a Node/Postgres application that will be deployed to Heroku. During my attempts to launch the app in a production environment, I encountered a timeout error. According to Heroku, this error is likely due to database or por ...

Mastering the art of utilizing callback functions

As a newcomer to Javascript and Jquery, I am still learning the basics. One thing that confuses me is how javascript executes each line as it encounters it. In a certain scenario (when my value is greater than 9), the custom alert will trigger and the wind ...

Adding an id to a ul tag using JavaScript

I am trying to dynamically add an ID called "myMenu" using JavaScript to a ul element for a search filter. Unfortunately, I am unable to directly access the ul tag to change it, so I need to do it via JavaScript. As I am new to JavaScript, I am looking t ...

The AngularJS page on my website is currently stuck in the mobile version, and strangely, the Google Chrome console is

When browsing our AngularJS website in mobile view on Google Chrome, it gets stuck and becomes unresponsive. The developer console does not show any error messages during this time. To replicate the issue, switch to mobile view, click on the "All top compa ...

Creating dynamic components with constructor parameters in Angular 9

Having trouble passing a value to the constructor in the component generation code. Check out the original code here: https://stackblitz.com/edit/angular-ivy-tcejuo private addComponent(template: string) { class TemplateComponent { @ViewChild( ...

Callback function not being triggered in Jquery's getJson method

I am currently faced with a javascript conundrum. Below is the snippet of code that I have been working on: $.get("categories/json_get_cities/" + stateId, function(result) { //code here }, 'json' ); ...

Utilizing ReactJS to display a new screen post-login using a form, extracting information from Express JSON

I am facing a challenge with updating the page on my SPA application after a successful login. I have successfully sent the form data to the API using a proxy, but now the API responds with a user_ID in JSON format. However, I'm struggling with making ...

Do you mean using a JSON object as a value?

When creating a JSON object where the value itself is an object, what is the correct way to write it? var data ='{"phone":{"gtd": "080"}}'; OR var data ='{"phone":"{gtd: 080}"}'; This question may seem straightforward. I am curious ...

Text box is not automatically filling up when selecting from dropdown menu

I am currently facing an issue with a dropdown box that offers three different selections. I want the Group ID associated with the selected group to automatically populate in the textbox below. How can I achieve this functionality? Whenever I make a selec ...

Show the user's name in an Express partial once they have logged in

I've been trying to find a solution for my issue without success. Here's the scenario: I have a homepage ('/'), a profile page ('/profile'), and a login/register page. I'm using passport with local, twitter, and google fo ...

The alert box for model validation summary errors is deactivated when hidden using .hide() method

In my MVC web application form, there is an optional postcode finder. If there is no match for the entered postcode, I add a custom error message to the .validation-summary-errors section. After the error is fixed, I remove all instances of the postcode cl ...

Switch out a visual element for Dropzone.js

During my recent project, I utilized Dropzone.js for image uploads. However, I am now interested in transforming the dropzone area into an actual image. For instance, if there is a "featured image" attached to an article, users should be able to drag and ...

Wiki experiencing issues with NodeJS HttpGet functionality

Goal Retrieve the HTML content of a Wiki Page. Introduction In an attempt to fetch the HTML of a Wiki page () for data parsing purposes, I am utilizing NodeJS and its HTTP Request methods. Code Snippet Below is the simple code snippet that accesses th ...

Ways to detach event listener in Vue Component

One of my Vue2 components has a custom eventListener that I added in the mounted lifecycle hook. I am now trying to figure out the correct way to remove this listener when the component is destroyed. <template> <div> ... </di ...

Syntax Error: The function `loadReposFromCache(...).error` is not defined in this building

I'm currently attempting to utilize the SyntaxHighlighter v4 plugin, but I'm facing issues with the build process! While following the guidelines provided here, an error popped up: $ ./node_modules/gulp/bin/gulp.js setup-project [10:12:20] Requ ...

Error message thrown: "The reference to $ is undefined. Are you using Jsfiddle?"

As a newcomer to javascript, I decided to experiment with creating a navigation bar that only appears when the user scrolls down using JSFiddle. However, when I transferred the code to Dreamweaver, it stopped functioning. Why is this happening? I've ...