我正在尝试使用单页应用程序示例(淘汰教程)和映射插件来创建用户可以单击(选择)的项目列表。我需要从一开始就选择一个默认项目,这是映射插件不起作用的地方,尽管它适用于裸淘汰赛。我错过了什么吗?或者你如何驯服映射插件?
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() }不会在初始页面加载时评估。知道为什么非常感谢!