1

我有数组列表,比如说 table#1,table#2,... table#10

我想单击表号,然后在面板中显示该表的列表项。

这是片段代码。

HTML,唯一的问题是这一行。我想在单击列表编号时动态更改编号并刷新。

<div data-bind="foreach: table[number].lines">  //  <--  this  line
            <p>
                <span data-bind="text: name"></span>, 
                <span data-bind="text: qty"></span> @
                <span data-bind="text: price"></span> = 
                <span data-bind="text: extendedPrice"></span>
            </p>
        </div>

对象数组

var table = new Array();
table[0] = new tableClass('one');
table[1] = new tableClass('two');
table[2] = new tableClass('three');
table[3] = new tableClass('four');

申请KO

ko.applyBindings(table, $('#tablePos').get(0));

我不想使用更多的部分绑定。因为我在这个页面中使用了太多的绑定。

谢谢你们

4

2 回答 2

2

您应该在 ViewModel 中创建一个可观察的 currentTable

var currentTable = ko.observable(table[0]);

并将其绑定到 currentTable

<div data-bind="foreach: currentTable.lines">

当您更改表格时,只需执行以下操作:

currentTable(table[2]);

.

function InitViewModel() {
    function ViewModelFunction() {
        this.currentTable = ko.observable(table[0]);

        ... more observables

    }
    window.ViewModel = new ViewModelFunction();

    ko.applyBindings(window.ViewModel);
}

$(document).ready(function () {
    InitViewModel();
});

var table = new Array();
table[0] = new tableClass('one');
table[1] = new tableClass('two');
table[2] = new tableClass('three');
table[3] = new tableClass('four');

function onSomeEvent(number) {
    window.ViewModel.currentTable(table[number]);
}

...
as many bindings as you want to observables in the ViewModel
...
于 2013-08-22T18:46:30.590 回答
1

您可以将表保存在 observableArray 中并通过索引检索它们。

self.SelectedIndex = ko.observable(0); // save index of selected table
self.List = ko.observableArray([]); // list to save your tables

// Retrieve your selected table by ko.computed
self.SelectedList = ko.computed(function() {
    return self.List()[self.SelectedIndex()];
});

// ... init your tables or sth below

这就是解决你问题的方法。当我显示数据时它有点复杂,所以不要注意到它们。

于 2015-09-19T16:07:25.190 回答