我花了一些时间试图弄清楚为什么绑定不起作用而没有成功'(在html部分中没有工作绑定)'。 我有一个简单的玩家列表;当点击其中一个时,我应该会在底部页面看到绑定的名称: 1)正确显示与vm.selectedPlayerName绑定的玩家名称 2)与vm.selectedPlayer.name()绑定的播放器名称仅在页面加载时正确显示,并且从不在click事件上显示,即使控制台日志在selectedPlayer对象中显示正确的更改也是如此。 我想让2)努力避免在视图模型中重新定义属性。 我做错了什么?
<!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>
答案 0 :(得分:2)
问题是你没有为SelectedPlayer observable分配东西:
goToDetails = function (aPlayer) {
my.vm.selectedPlayer = aPlayer;
...
},
应该是:
goToDetails = function (aPlayer) {
my.vm.selectedPlayer(aPlayer);
....
},
请记住,一个可观察物在技术上是一个功能。当您通过赋值运算符分配它时,您将其作为函数覆盖,将其替换为对象,该对象仅在挖掘模型中的页面加载时处理。