Knockoutjs simple cascading selects

China☆狼群 提交于 2019-12-25 05:43:39

问题


I'm trying to do a simple cascading combobox using knockoutjs. My first combobox binds to 2 properties in the viewmodel:

BusinessLines as the source for comboboxoptions

SelectedBusinessLine as the selected item in the first combobox.

Each BusinessLine has a collection of Clusters.

The second combox should data bind to the SelectedBusinessLine.Clusters observable for combobox options source, and SelectedCluster for the selected option.

The problems is that the second combobox doesn't get populated at all.

Source in JsFiddle (In JsFiddle the first binding doesn't work either, sry firs time use)

JavaScript

 var mainViewModel = null;

    $(document).ready(function() {

        var mainViewModelData = <%= JsonConvert.SerializeObject(NewRequestViewModel) %>;

        mainViewModel = ko.mapping.fromJS(mainViewModelData);

        ko.applyBindings(mainViewModel);

    });

HTML

<div>
    <table>
        <tr>
            <td>
                Business Line
            </td>
            <td>
                <select data-bind="options: BusinessLines,
                                   optionsText: 'Title',
                                   value: SelectedBusinessLine,
                                   optionsCaption: 'Select Business Line..'">
                </select>
            </td>
        </tr>
        <tr>
            <td>
                Cluster
            </td>
            <td>
                <select data-bind="options: SelectedBusinessLine.Clusters,
                                   optionsText: 'Title',
                                   value: SelectedCluster,
                                   optionsCaption: 'Select Cluster..'">
                </select>
            </td>
        </tr> 
    </table>
</div>

Update:

Second solution (without computed props)

<select data-bind="options: SelectedBusinessLine() ? SelectedBusinessLine().Clusters() : [],
                                   optionsText: 'Title',
                                   value: SelectedCluster,
                                   optionsCaption: 'Select Cluster..'">
                </select>

回答1:


Here is a working version:

http://jsfiddle.net/x2qMg/4/

Your fiddle wasn't working (at all) because you did not include the Knockout Mapping JS reference (the mapping plugin in not part of the main Knockout JS) - see the Manage Resources area in the left side bar.

You'll see the biggest change I made was to use a with binding to only render Clusters when a Business Line has been selected. Also note that I had to use $root.SelectedCluster as otherwise it would not be found within the Selected Business Line context created by the with.



来源:https://stackoverflow.com/questions/11386624/knockoutjs-simple-cascading-selects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!