我有几个小时的淘汰赛经验,我正在尝试修改现有的淘汰赛应用程序。它使用挖空中的模板来呈现选择列表的列表。
Tmpl文件:
<select data-bind="options: $root.AccountIDDropList, optionsText: 'AccountID', optionsValue: 'AccountID', value: selectedAccountID.AccountID, optionsCaption:'-- Select Account --' "></select>
HTML文件:
<div style='margin-left: 5px;' data-bind="template: { name: 'Bank', foreach: Account }"></div>
渲染此图像时,我会得到一个带有帐号的选择列表列表,但是由于每个列表都被命名为 selectedAccountID.AccountID ,因此当我尝试从每个列表中获取值时,我只能获得最后一个。
var AccountModel = function(data){
var self = this;
...
};
var viewModel = function(data) {
var self = this
self.selectedAccountID = ko.observable();
self.sendMe = function(){
alert(ko.toJSON({
this.selectedAccountID(),
}));
};
};
ko.applyBindings(new viewModel());
答案 0 :(得分:0)
您的请求有些含糊,但是您如何看待该解决方案
var AccountModel = function(id, name) {
var self = this;
self.id = id;
self.name = name;
};
ko.applyBindings(() => {
var self = this;
self.accountList = [
new AccountModel(1, 'foo'),
new AccountModel(2, 'bar'),
new AccountModel(3, 'stack'),
new AccountModel(4, 'overflow')
];
self.accountSelectedList = ko.observableArray([]);
self.addAccount = () => self.accountSelectedList.push(ko.observable(self.accountList[0]));
self.removeAccount = (index) => self.accountSelectedList.splice(index, 1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
<script type="text/html" id="accountTemplate">
<span data-bind="text: $index()"></span>
<select data-bind="options: accountList, optionsText: 'name', value: account"></select>
<a href="#" data-bind="click: () => { removeAccount($index()); }">x</a><br />
</script>
<p data-bind="template: { name: 'accountTemplate', foreach: accountSelectedList, as: 'account', noChildContext: true }"></p>
<p><input type="button" data-bind="click: addAccount" value="Add account" /></p>
<p data-bind="text: _.map(self.accountSelectedList(), function(r) { return `${r().id}: ${r().name}`; }).join(', ')"></p>