我正在试验淘汰赛事件。我在div中有三个按钮(“包装”,“开拓者”和“道奇队”)。每个按钮的数据联盟属性分别为“ NFL”,“ NBA”和“ MLB”。当我单击div时,我希望ViewModel中的click事件处理程序以团队和他们直接参与的联赛的名称传递。我目前正在做的工作是从提供给处理程序的event参数中获取值-但处理该事件(尤其是命名的HTML属性)似乎与MVVM模式相反。
<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());
}
}
})();
**编辑-下面的代码笔经过编辑以反映Jeff Mercado的回答,现在使用TypeScript,更采用MVVM精神**
答案 0 :(得分:1)
出于这个原因,您确实应该在按钮本身而不是父元素上应用click事件处理程序。
您应该更改模型以容纳代表团队的对象,并让点击处理程序使用这些对象。
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>