1

我正在尝试使用单页应用程序示例(淘汰教程)和映射插件来创建用户可以单击(选择)的项目列表。我需要从一开始就选择一个默认项目,这是映射插件不起作用的地方,尽管它适用于裸淘汰赛。我错过了什么吗?或者你如何驯服映射插件?

HTML部分:

<ul data-bind="foreach: gamePlayers">
    <li class="clickable" data-bind="
              text: playerName, 
              css: { selected: playerId == $root.chosenPlayerId() },                              
              click: $root.selectPlayer">
    </li>
</ul>

JS 常用部分:

var dataJS = {
    gamePlayers: [{playerId:1, playerName:"Sun"},{playerId:2,playerName:"Moon"}],
    playerActive:1
};

确实有效的JS:

function GameViewModel(data) {
    // Data
    var self = this;
    self.gamePlayers = ko.observableArray(data.gamePlayers);
    self.chosenPlayerId = ko.observable();

    // Behaviours    
    self.selectPlayer = function (player) { self.chosenPlayerId(player.playerId); };
    self.selectPlayer(data.gamePlayers[0]);
}

ko.applyBindings(new GameViewModel(dataJS));

JS不起作用:

my.vmPlayers = {};

function MyViewModel (data) {
    var self = this;
    ko.mapping.fromJS(data, {}, self);
    self.chosenPlayerId = ko.observable();
    self.selectPlayer = function (player) { self.chosenPlayerId(player.playerId); };
    self.selectPlayer(data.gamePlayers[0]);
}

var mapping = {
    create: function (options) {
        return new MyViewModel(options.data);
    }
};

my.vmPlayers = ko.mapping.fromJS(dataJS, mapping);
ko.applyBindings(my.vmPlayers);

它如何不起作用的示例http://jsfiddle.net/HeroEja/43AtS/

所以这个绑定css: { selected: playerId == $root.chosenPlayerId() }不会在初始页面加载时评估。知道为什么非常感谢!

4

1 回答 1

1

主要问题是由这一行引起的:

self.chosenPlayerId(data.playerActive);

因为在这种情况下data不会是 JS 对象,而是data持有 JSON 字符串本身,因此data.playerActive将返回 undefined 并且您的初始选择将不起作用。

你需要的是:

self.chosenPlayerId(self.playerActive());  

因为无论如何您将数据映射到selfwithko.mapping.fromJS(data, {}, self);

并且由于映射插件playerId将是可观察的,因此您需要相应地更改您的用法以使其工作

所以在你的css绑定中:

css: { selected: playerId() == $root.chosenPlayerId() }

在你的selectPlayer方法中:

self.selectPlayer = function (player) {
    self.chosenPlayerId(player.playerId());
};

一个固定的演示JSFiddle

于 2013-03-15T08:48:46.150 回答