objects bound to knockout binding effects

I have been struggling to understand why the binding is not working as expected for the ‘(not working binding on click)’ in the HTML section. I have a basic list of Players, and when I click on one of them, the bound name should change at the bottom of the page: 1) The player name bound with vm.selectedPlayerName appears correctly. 2) The player name bound with vm.selectedPlayer.name() only shows up correctly during page load and never updates on the click event, despite the selectedPlayer object changing properly (as seen in the console log). I want to fix issue 2) so that I don't have to redefine properties in the view model. What could be causing this problem?

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>
<script type='text/javascript' src='http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js'></script>
<script>
    $(document).ready(function () {
        var my = {}; //my namespace
    // Player
    my.Player = function () {
        this.name = ko.observable("");
    };

    // The ViewModel
    my.vm = function () {
        var
        players = ko.observableArray([]),
        selectedPlayer = ko.observable(),
        selectedPlayerName = ko.observable(""),

        goToDetails = function (aPlayer) {
            my.vm.selectedPlayer = aPlayer;
            my.vm.selectedPlayerName(my.vm.selectedPlayer.name());
            console.log("goToDetails: ", my.vm.selectedPlayerName());
        },

        loadPlayers = function () {
            my.vm.players.push(new my.Player().name("Player1"));
            my.vm.players.push(new my.Player().name("Player2"));
            my.vm.players.push(new my.Player().name("Player3"));
            my.vm.selectedPlayer = my.vm.players()[0];
            my.vm.selectedPlayerName(my.vm.selectedPlayer.name());
        };

        return {
            // Data
            players: players,
            selectedPlayer: selectedPlayer,
            selectedPlayerName: selectedPlayerName,
            // Other
            loadPlayers: loadPlayers,
            goToDetails: goToDetails,
        };
    }();

    my.vm.loadPlayers();
    ko.applyBindings(my.vm);
    });
</script>
<title></title>
</head>
<body>
<table>
    <thead>
        <tr>
            <th>Name</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: players">
        <tr>
            <td data-bind="text: name, click: $root.goToDetails"></td>
        </tr>
    </tbody>
</table>
<p>
    Selected player (working binding on click): <span data-bind='text:  $root.selectedPlayerName'></span>
    <br />
    Selected player (not working binding on click): <span data-bind='text:  selectedPlayer.name()'></span>
</p>

</body>

Answer №1

The issue lies in not properly assigning a value to the SelectedPlayer observable:

 goToDetails = function (aPlayer) {
       my.vm.selectedPlayer = aPlayer;
       ...
  },

To correct this, the code should be updated as follows:

 goToDetails = function (aPlayer) {
       my.vm.selectedPlayer(aPlayer);
       ....
  },

It's important to remember that an observable is actually a FUNCTION. By using the assignment operator, you are replacing the function with an object, which will only take effect during page load in the knockout 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

Modify content or display picture within accordion panel based on its identifier

In my view, I have a model representing a list of items. Each item has a unique ID, which is included in the H2 header tag. The details of each item are displayed in a div below the header. Initially, there is an image within the header that is set to disp ...

What is the best method for retrieving an item from localstorage?

Seeking advice on how to retrieve an item from local storage in next.js without causing a page rerender. Here is the code snippet I am currently using: import { ThemeProvider } from "@material-ui/core"; import { FC, useEffect, useState } from "react"; i ...

When the only source is available, the image undergoes a transformation

Is there a way to dynamically adjust the height of an image using JQuery or JavaScript, but only when the image source is not empty? Currently, I have an image element with a fixed height, and even when there is no source for it, Chrome still reserves sp ...

Understanding the process of parsing JSON response using JavaScript

I am facing an issue with reading a JSON object in JavaScript. I have received this JSON object as a response and now I need to create a jstree based on it. Here is my JavaScript code: var repoId = $('#frmHdnV').val(); // variable to hold req ...

The error message "TypeError: res.json is not a function in express.router" indicates that

I encountered the following error message and I'm not sure how to resolve it: TypeError: res.json is not a function I have reviewed the express documentation but couldn't find any syntax errors or issues. Here is my code: index.js import expr ...

Combining jQuery methods and selectors within a loop

Can a sequence of selectors and methods be generated within a loop? For instance, assuming an array of elements is given: array[0] = '.type1value1, .type1value2, .type1value3'; array[1] = '.type2value1, .type2value2, .type2value3'; ar ...

Troubleshooting: jQuery ajax form is not functioning as expected

After attempting various methods to create a basic jQuery Ajax form, I am puzzled as to why it is not submitting or displaying any notifications. Below is the code I have been working with: Javascript ... <script type="text/javascript" src="assets/js ...

What is the process for configuring my form to automatically send to my email upon clicking the send button?

I found this code snippet on a website and I'm trying to figure out how to make the 'Send!' button redirect users to my email address with their message, name, and email included. Can anyone help me solve this issue? I attempted to add my e ...

Conceal any elements designated by a particular class and reveal them based on their corresponding ID

I have utilized jQuery's hide() function to initially hide all elements of a specific class when the page loads. My goal is to make individual elements visible again based on their unique IDs when a corresponding link is clicked. In total, there are ...

Executing a Knex RAW MySQL query to insert new records into a database table

As someone new to working with MySQL, I have previously used PSQL in a similar manner. However, the following code is generating an error. return await db .raw( `INSERT INTO users(firstName, lastName, email, ...

Guide on transferring control from a successful jQuery event to an HTML form

I am currently using the following jQuery code to validate user details. $.ajax({ type: "POST", url: "Login", data:'uname='+encodeURIComponent(uname)+'&'+'pass='+encodeURIComponent(pass), ...

Incorporating a JavaScript workflow into Django

Currently, I am following a tutorial on integrating a modern JavaScript pipeline into my Django application. The objective is to have the JavaScript code write "Hello webpack" onto the page, but unfortunately, it is not displaying as expected. Since I alr ...

What is the best way to insert a Button within a Tab while ensuring that the indicator remains in the appropriate tab?

Is it possible to include a button inside a Tab? When I click on "Homepage", the tab switches correctly with the indicator showing on the right tab. However, when I click on "Profile", the indicator moves to the logout button instead. How can I fix this ...

Error: Identical div IDs detected

<div id="tagTree1" class="span-6 border" style='width:280px;height:400px;overflow:auto;float:left;margin:10px; '> <a class="tabheader" style="font-size:large">Data Type</a><br /> <div class="pane">Refine sea ...

The problem with the first item title in the Jquery slider is causing

I've been working on setting up a Jquery slider (caroufredsel) in which I want certain elements to be displayed above the slider itself, outside of the wrapper. Everything is working fine except for the first slide! After spending several days trying ...

Reveal Visual Content upon Hovering

Is there a way to show an image only when the mouse hovers over it? Additionally, can we underline the adjacent text at the same time? If the mouse moves away from the image, I'd like it to hide again and revert the text back to its original state. T ...

Using a Do/While loop in combination with the setTimeout function to create an infinite loop

Having trouble with this script. The opacity transition works fine, but there seems to be an issue with the loop causing it to run indefinitely. My goal is to change the z-index once the opacity reaches 0. HTML <div class="ribbon_services_body" id="ri ...

Replace the image source with a list of images

I am looking to create a dynamic image list using either an array or an HTML list. When I hover over an image, it should change one by one with a fade or slide effect, and revert back to the default images when I hover out. Question 1: What type of list s ...

Tips on utilizing recursive Promises within a loop while transferring arguments to another function

Despite searching other threads on SO, I couldn't find a satisfactory answer to my problem. Every solution seems to be missing something essential for my case, especially since none of them address Apple Music specifically. The Apple API relies heavil ...

The Firebase 'not-in' operator is malfunctioning

Within my database, there is a document located at: https://i.stack.imgur.com/OTZpd.png I am attempting to query the number of messages documents where the user's ID does not appear in the "read_by" array. This is the code I am currently using: const ...