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 **