0

我花了一些时间试图弄清楚为什么绑定在 html 部分中的“(单击时不工作的绑定)”没有成功的情况下无法工作。我有一个简单的玩家列表;单击其中一个时,我应该在底部页面中看到绑定名称发生变化:1)与 vm.selectedPlayerName 绑定的玩家名称正确显示 2)与 vm.selectedPlayer.name() 绑定的玩家名称仅在以下位置正确显示即使控制台日志显示 selectedPlayer 对象发生了适当的更改,页面加载时间也不会出现在 click 事件上。我想让 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>

4

1 回答 1

2

问题是您没有为 SelectedPlayer observable 分配一些东西:

 goToDetails = function (aPlayer) {
       my.vm.selectedPlayer = aPlayer;
       ...
  },

应该:

 goToDetails = function (aPlayer) {
       my.vm.selectedPlayer(aPlayer);
       ....
  },

请记住,一个可观察对象在技术上是一个函数。当您通过赋值运算符对其进行分配时,您将其作为一个函数覆盖,以将其替换为一个对象,该对象仅在淘汰模型中的页面加载时得到处理。

于 2013-02-03T17:53:38.933 回答