0

我有 2 个从可观察数组填充的下拉列表。第二个由第一个结果过滤。这工作正常。即使第二个 id 的值是在绑定之前设置的,绑定似乎会擦除它并且不会再次更改它。

我也不明白为什么它不会显示viewModel的json。

html

 <p>
     <label>Serial Number</label>
     <span data-bind="text: PartNumber"></span>
     <span data-bind="text: Revision"></span>
     <span data-bind="text: SequenceNumber"></span>
</p>      

<label>Description</label>        
<input data-bind="value: Description" />

<label>Usage</label>
<select data-bind="options: UsageTypes, optionsText: 'UsedType', optionsValue: 'UsedTypeID', value: UsedTypeID"></select>
<select data-bind="options: UsageFiltered, optionsText: 'UsedOn', optionsValue: 'UsedOnID', optionsCaption: 'select...', value: UsedOnID, visible:UsedTypeID"></select>

<p data-bind="text: ko.toJSON(viewModel)"></p>

javascript

var data = {"PartNumber":"SAMPLE123456","Revision":"D","SequenceNumber":"1","SerialNumber":"SAMPLE123456D001","Description":"This is a test","SupplierID":"4","UsedTypeID":"U","UsedOnID":0} ;

var viewModel = ko.mapping.fromJS(data);

viewModel.UsageTypes = ko.observableArray( [{"UsedTypeID":"P","UsedType":"Product"},{"UsedTypeID":"S","UsedType":"Series"},{"UsedTypeID":"U","UsedType":"Unknown"}]);
viewModel.UsagesList = ko.observableArray(
[{"UsedTypeID":"P","UsedType":"Product","UsedonID":14,"UsedOn":"banana"},
 {"UsedTypeID":"P","UsedType":"Product","UsedonID":16,"UsedOn":"kjhkjhkj"},
 {"UsedTypeID":"P","UsedType":"Product","UsedonID":7,"UsedOn":"prod1234"},
 {"UsedTypeID":"P","UsedType":"Product","UsedonID":15,"UsedOn":"things"},
 {"UsedTypeID":"P","UsedType":"Product","UsedonID":20,"UsedOn":"thinkgs2"},
 {"UsedTypeID":"S","UsedType":"Series","UsedonID":17,"UsedOn":";lkgd;ldf"},
 {"UsedTypeID":"S","UsedType":"Series","UsedonID":18,"UsedOn":"df;lkjdflk"},
 {"UsedTypeID":"S","UsedType":"Series","UsedonID":13,"UsedOn":"fdsdfsdf"},
 {"UsedTypeID":"S","UsedType":"Series","UsedonID":12,"UsedOn":"mn,m,m,"},
 {"UsedTypeID":"S","UsedType":"Series","UsedonID":19,"UsedOn":"rubberchicken"},
 {"UsedTypeID":"S","UsedType":"Series","UsedonID":11,"UsedOn":"sdfsdfsdf"},
 {"UsedTypeID":"U","UsedType":"Unknown","UsedonID":0,"UsedOn":"Unknown"}]);

viewModel.UsageFiltered = ko.computed(function(){
    var filter = this.UsedTypeID();
    if (!filter){
        return this.UsagesList();
    } else {
        return ko.utils.arrayFilter(this.UsagesList(), function(item) {
            return filter === item.UsedTypeID    
        }); 
    }
}, viewModel);

ko.applyBindings(viewModel);

见小提琴

4

1 回答 1

0

我添加了一个计算方法,该方法返回 JSON 并将其绑定到段落标记的 HTML,并且它起作用了。

<p data-bind="html: jsonText"></p>


viewModel.jsonText = ko.computed(function(){
    return ko.toJSON(viewModel);
}, viewModel);

在这里更新了你的小提琴:

http://jsfiddle.net/5rg6e/5/

于 2013-01-23T00:39:10.787 回答