Passing the value of the attribute from event.target as a parameter in a knockout click event

I have been exploring knockout events and am currently working on a functionality involving three buttons ("Packers", "Trail Blazers", and "Dodgers") within a div. Each button is associated with a data-league attribute of "NFL", "NBA", and "MLB," respectively. My goal is to have the click event handler in the ViewModel receive the name of the team and the league they belong to directly when the div is clicked. While I have managed to extract this information from the event parameter provided to the handler, it feels like working with the event and specific named HTML attributes contradicts the essence of the MVVM pattern.

<div data-bind="click: doSomething">
  <button data-league="NFL">Packers</button>
  <button data-league="NBA">Trail Blazers</button>
  <button data-league="MLB">Dodgers</button>
</div>
<span data-bind="text: myObservable"></span>

(function() {
  window.onload = function(e) {
    try {
      var myViewModel = {
        myObservable: ko.observable("Initial Value"),
        doSomething: (viewModel, event) => {
          console.log("doSomething is executing")
          //How can I avoid using event.target.attributes in the viewModel code below and
          //instead have the data-league value passed in as a parameter?
          if(event.target.attributes["data-league"]){
            let league = event.target.attributes["data-league"].value
            let team = event.target.innerText
            viewModel.myObservable("The " + team + " are an " + league + " team")  
          }

        }
      }

      ko.applyBindings(myViewModel)

    } 
    catch (ex) {
      console.log(ex.toString());
    }
  }
})();

** EDIT - The codepen below was edited to reflect Jeff Mercado's answer and is now in TypeScript and more in the MVVM spirit **

https://codepen.io/Walkipedia/pen/jONjweq?editors=1111

Answer №1

It is recommended to assign the click event handler directly to the buttons themselves instead of their parent element for better functionality.

Rather than manipulating the DOM directly, consider updating your model to store team objects and refer to them in your event handler.

const myViewModel = {
  myObservable: ko.observable("Initial Value"),
  teams: [
    { league: "NFL", team: "Packers" },
    { league: "NBA", team: "Trail Blazers" },
    { league: "MLB", team: "Dodgers" }
  ],
  doSomething: ({league, team}) => {
    console.log("doSomething is executing");
    myViewModel.myObservable(`The ${team} are an ${league} team`);
  }
};
<div data-bind="foreach: teams">
  <button data-bind="click: $root.doSomething, text: team"></button>
</div>
<span data-bind="text: myObservable"></span>

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

"Observed Issue: Ionic2 Array Fails to Update in HTML Display

I am struggling with updating an array in Ionic2 and Angular2. I have tried updating it on the front end but it's not working, even though it updates perfectly on the backend (ts) as confirmed by checking the console. I need assistance with this. Her ...

Issue encountered while generating dynamic Routes using the map function

When attempting to dynamically use Route from an array, I encounter an error. Warning: Incorrect casing is being used. Use PascalCase for React components, or lowercase for HTML elements. The elements I am utilizing are as follows: const steps = [ { ...

Currently honing my skills in Angular 2, but encountering an error stating "Bindings cannot contain assignments."

<app-employeecount [all]= "gettotalemployeescount()" <app-employeecount [all]= "gettotalemployeescount()" [male]= "gettotalmaleemployeescount()" [female]="gettotalfemaleemployeescount()" (on ...

The connection named "default" was not located

Error ConnectionNotFoundError: Connection "default" was not found. I encountered this error when I implemented the dependency inversion principle in my project. ormconfig.json { "name": "default", "type": " ...

Angular - Electron interface fails to reflect updated model changes

Whenever I click on a field that allows me to choose a folder from an electron dialog, the dialog opens up and I am able to select the desired folder. However, after clicking okay, even though the folder path is saved in my model, it does not immediately s ...

Can someone please explain how to bring in the Sidebar component?

click here for image description check out this image info An issue arises as the module '@components/Sidebar' or its type declarations cannot be located.ts(2307) Various attempts were made, including: import Sidebar from '@components/Sid ...

The property 'x' cannot be found on the data type 'true | Point'

I am dealing with a variable named ctx which can be either of type boolean or Point. Here is how Point is defined: type Point = { x: number y: number } In my React component, I have the following setup: const App = () => { const [ctx, toggleC ...

Struggling with getting Typescript async/await to function properly

I'm experiencing an issue with async/await in TypeScript targeting es2017. Here is the code snippet that's causing trouble: My route.ts : method: 'POST', config: { auth: { strategy: &apo ...

What is the best way to modify an existing object in an Observable Array in Angular?

As I work on my Ionic 5 / Angular application, a challenge arises when attempting to update a Conversation object within the existing array of Conversation: private _conversations = new BehaviorSubject<Conversation[]>([ new Conversation( & ...

Mixing TypeScript generic types loosely

Let's explore a simple example of typescript mixins: import { Observable, of } from 'rxjs'; class Service<TDataType> { public foo(f: TDataType): Observable<TDataType> { return of(f); } } type GConstructor<T = {}> = new ...

Expand the data retrieved from the database in node.js to include additional fields, not just the id

When creating a login using the code provided, only the user's ID is returned. The challenge now is how to retrieve another field from the database. I specifically require the "header" field from the database. Within the onSubmit function of the for ...

What could be causing the DOM not to update after updating the data set in Angular 2?

Currently, I am facing an issue in Angular 2 where I call a function of a child component from the parent. The child function updates my data set which initially loads the HTML. However, when I call the function again while on the same HTML, it displays in ...

Using TypeScript to specify data types in the Vue data object

I am currently utilizing Vue.js with Typescript in a webpack project. Following the guidelines provided in the Recommended Configuration in my tsconfig.json, I have set: "strict": true, Within one of my components, I have: declare interface P ...

Is there a way to achieve region collapsing and expanding using #region / #endregion in TypeScript within Visual Studio Community Edition 2019?

For a while now, we've been utilizing "region collapsing" in TypeScript as shown below: //#region GUI handlers ...code related to handling GUI events... //#endregion This method has functioned well in VS2015 CE and VS2017 CE, with a small "-" or "+" ...

Unable to reinitialize the DataTable using Angular Datatable

I've been working on an Angular application that has a simple CRUD functionality. Initially, I tested my data with a static HTML table and everything was functioning as expected. However, I decided to implement a data table framework called Angular da ...

How to effectively implement forwardRef with HOC in TypeScript

I'm currently working on developing a React Higher Order Component (HOC), but I've run into some issues along the way. Here's a snippet of my code: import React, { type FC, forwardRef } from 'react' import { ButtonBase, ButtonBaseP ...

Disable the functionality of the device's back button to prevent it from going back to the

For my project, I utilize popups to display important information to the user. When a popup is displayed, how can I override the functionality of the device's back button so that instead of navigating to the previous route, it will close the popup? ...

How to dynamically assign a type based on a single choice from multiple options (props)

I have a props object that includes: { option1, option2, option3, option4, general, otherProps } The requirement is to allow only one option to be used at a time. Here are the types defined: interface MyTypes { option1: boolean option2: boolean option3 ...

Leveraging AWS CDK to seamlessly integrate an established data pipeline into your infrastructure

I currently have a data pipeline set up manually, but now I want to transition to using CDK code for management. How can I achieve this using the AWS CDK TypeScript library to locate and manage this data pipeline? For example, with AWS SNS, we can utilize ...

Creating object interfaces in TypeScript dynamically based on function parameters

I'm currently working on a small project that involves creating lists of products in a certain format. For example: let products = createList( new Product('product1'), new Product('product2') ) When it comes to accessing a s ...