具有现有id值的Knockout Cascading Dropdown

时间:2013-01-22 23:56:41

标签: javascript knockout.js

我从可观察数组中填充了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);

See Fiddle

1 个答案:

答案 0 :(得分:0)

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

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


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

在此处更新了您的小提琴:

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