我正在尝试使用单页应用程序示例(淘汰教程)和映射插件来创建用户可以单击(选择)的项目列表。我需要从头开始选择一个默认项目,这是映射插件无法工作的地方,尽管它适用于裸露的淘汰赛。我错过了什么吗?或者你如何驯服映射插件?
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()} 。任何想法为什么非常感谢!
答案 0 :(得分:1)
主要问题是由这一行引起的:
self.chosenPlayerId(data.playerActive);
因为在此上下文中data
不是JS对象,但 data
持有JSON字符串所以data.playerActive
将返回undefined并且您的初始值选择不起作用。
您需要的是:
self.chosenPlayerId(self.playerActive());
因为您无论如何都将数据映射到self
ko.mapping.fromJS(data, {}, self);
由于映射插件playerId
将是可观察的,因此您需要相应地更改您的用法以使其正常工作
所以在你的css绑定中:
css: { selected: playerId() == $root.chosenPlayerId() }
并使用selectPlayer
方法:
self.selectPlayer = function (player) {
self.chosenPlayerId(player.playerId());
};
固定演示JSFiddle。