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

Tips for managing and capturing errors in Express

const database = require('database'); const express = require('express'); const app = express(); const cors = require('cors'); app.use(cors()); const bodyParser = require('body-parser'); const urlencodedParser = body ...

Having trouble getting CSURF (CSRF middleware) to function properly with XSRF in AngularJS

Struggling to get the CSRF middleware working with Express and Angular? You're not alone. Despite various guides on the internet, the process remains unclear. Express 4.0 uses csurf as its CSRF middleware, while Angular requires setting X-XSRF-TOKEN. ...

Enhance the php query limit using javascript when loading additional content

Hey there, currently working on implementing a reverse infinite scroll feature for a private messaging module. Everything seems to be functioning well, except for one issue I'm facing - struggling to update the query limit. I set the maximum and lim ...

`Javascript often returns NaN for basic calculations`

Hello, I am currently developing a basic calculator for a game but I have encountered an issue. Despite having just started learning this programming language and reading all available tutorials, I am now in the process of writing code to gain more experie ...

Is there a way to display my array within my React component using JavaScript?

I am working with an element that looks like this: const DropdownElements = [ { key: 1, title: "City", placeholder: "Select City", apiUrl: "https://api.npoint.io/995de746afde6410e3bd", type: "city&qu ...

Best practice for structuring an object with multiple lengthy string elements in the GCP Datastore Node Library

My JavaScript object is structured like this: const data = { title: "short string", descriptions: [ "Really long string...", "Really long string..." ] } I need to exclude the long strings from the indexes, but I ...

Continuously update in JavaScript based on a condition, cease updating when the condition no longer

I have a scenario on my page where specific data needs to be refreshed every minute, but at the same time, the user should be able to view and edit certain modals. I want to ensure that when a modal is open, the data refreshes are paused so that the modal ...

Tips on expanding the space between words in a scrolling "marquee" text

Looking for some assistance with my jQuery project involving a horizontal scrolling "marquee" text. I am currently trying to adjust the size of the gap between the phrases in the marquee. Here is an example with the phrase "HEY THERE". jQuery(document ...

Navigating through Node and Express on Azure App Service

I'm facing an issue that I am not sure if it is related to Node or Azure App Service, so here's the situation: In my Node/Express app, I have defined two routes: router.get("/users", checkAuthHeader, userController.getUsers); router.po ...

Tips on storing the amount of time a user devotes to answering questions on my form into a database

I am facing an issue with storing the "duration" in my database. The "duration" I aim to store is the time spent by the user answering a question I created. When they click the submit button, I want to save the duration they spent in the database. Below i ...

Selecting HTML5 data attributes using jQuery

There is a button on my page with multiple data attributes, and I am trying to hide it by selecting it based on its class and two specific data attributes. <a href='#' class='wishlist-icon' data-wish-name='product' data-wi ...

What methods can be used to broaden configuration variables within VSCode using an extension?

I attempted to develop an extension for vscode that requires reading the pasteImage.parth variable from the ./vscode/settings.json file { "pasteImage.path": "${workspaceRoot}/assets/images" } In my attempt to retrieve the variable us ...

Names changes and deletion of files that have been uploaded- Using Vue.js

I attempted to use v-model in order to rename files before uploading them to the system, but unfortunately, it was not successful. As a result, I developed an alternative solution which is functioning perfectly, except for the fact that I am unable to reta ...

Can a dynamic react component be inserted into a standalone HTML document without the need for file downloads or server support?

I am implementing React for a Single Page Application (SPA) project where users can customize a component's font size, color, etc., and then embed this customized component into their website. I'm looking for a way to bundle the component and pre ...

Definition of Angular 2 File

I have developed a custom Gantt chart library using D3 in vanilla JavaScript. Now, I am trying to integrate it into my Angular 2 application. After installing D3 via npm and adding the necessary type files and the Gantt chart module to node_modules, I enco ...

Error in Prisma: Unable to retrieve data due to undefined properties (attempting to access 'findMany')

Recently, I've been working on a dashboard app using Prisma, Next.js, and supabase. Encountering an issue with the EventChart model in schema.prisma, I decided to create a new model called EventAreaChart. However, after migrating and attempting to ex ...

What is the method for determining the size of a WeakMap?

I am working with a WeakMap that looks like the following: let newObj = new WeakMap(); let key1={"a":1}; let key2={"b":2}; let key3={"c":3}; newObj.set(key1,"value1"); newObj.set(key2,"value2"); newObj.set( ...

Determine the number of rows in an Excel spreadsheet using JavaScript

Currently, I am working on a codeigniter project where I need to upload an Excel file. However, before uploading the file, I want to display the number of records it contains. To achieve this, I decided to create a function within my script and then call t ...

Incorporating OpenRouteService into an Angular application on Stackbliz

I am encountering an issue with integrating OpenRouteService into my Stackblitz application. The component code is as follows: import { Component, OnInit } from '@angular/core'; import {Location} from '@angular/common'; import {Openro ...

What could be the reason for the unexpected undefined value of my ajaxurl variable?

Seeking assistance with implementing code to track mp3 plays in a Wordpress plugin using ajax-counter.js jQuery(document).ready(function($) { console.log(ChurchAdminAjax.ajaxurl); $("audio").bind("play", function(){ console.log(ChurchAdmin ...