0

我有一个场景,我试图将淘汰赛应用于一些问题。基本上我有这种用户界面

Add (create a new Select Box duo with delete button)

Select Box  (options = Json from ajax request)
Select Box  (options = Json from ajax request with param from 1st select)
Delete

Select Box 
Select Box 
Delete

ETC

我将每一行视为数组中的另一个小部件,因此为简单起见,我将其淘汰

var ViewModel = function (widgets) {

    var self = this;

    this.widgets= ko.observableArray(widgets);
    this.subWidgets= ko.observableArray();

    this.mySelections = ko.observableArray();

   this.selectedWidget.subscribe(function (name) {

        if (name != null) {
            $.ajax({
                url: '@Url.Action("AddSubWidgetsByName")',
                data: { name: name },
                type: 'GET',
                async: false,
                contentType: 'application/json',
                success: function (result) {

                    self.subWidgets(result);

                }
            });
        }
    } .bind(this));

    self.addWidget = function (widget) {
        self.mySelections.push({

            ??? profit
        });
    };

}
var viewiewModel = new ViewModel();
ko.applyBindings(viewiewModel);

$.ajax({
    url: '@Url.Action("AddFund")',
    type: 'GET',
    async: false,
    contentType: 'application/json',
    success: function (result) {

        viewModel.widgets(result);


    }
});
 <select id="widgets" 
                data-bind='
                    options: widgets, 
                    optionsValue : "Name", 
                    optionsText: "Name", 
                    optionsCaption: "[Please select a widgets]"'
                    value: selectedWidget,

>

我可以为每个小部件动态创建一个选择并将子小部件选择与 mySelections 数组中的项目相关联吗?我不能以这种方式使用 selectedWidget 的值绑定,因为所有下拉列表都以这种方式绑定在一起。我需要让他们独立 - 关于如何去做的任何想法?

干杯!

4

1 回答 1

0

这样做的一种方法是让每个小部件都有自己的视图模型(注意,这是来自 jsFiddle,所以 ajax 与他们的 echo API 一起工作,这需要 POST):

var Widget = function(){
var self = this;
self.selectedWidget = ko.observable('');
self.subWidgets = ko.observableArray([]);
self.selectedSubWidget = ko.observable('');

this.selectedWidget.subscribe(function (name) {
    if (name != null) {
        $.ajax({
            url:"/echo/json/",
            data: {
                json: $.toJSON(
                    [Math.floor(Math.random()*11),
                     Math.floor(Math.random()*11),
                     Math.floor(Math.random()*11)]
                ),
                delay: 1
            },
            type:"POST",
            success:function(response)
            {
                self.subWidgets(response);
            }
        });
    }
});

};

然后,您可以使用简单的视图模型轻松跟踪子选择和添加。这是完整的小提琴

于 2012-06-25T18:00:16.513 回答