如何将动态控件与 KNOCKOUTJS 一起使用

how do I use dynamic controls with knockoutjs

本文关键字:一起 KNOCKOUTJS 动态控件      更新时间:2023-09-26

我有一个场景,我正在尝试应用淘汰赛,但有一些问题。基本上我有这种用户界面

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

每一行我都视为数组中的另一个小部件,所以我的淘汰赛是为了简单起见

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,

>

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

干杯!

一种方法是使每个小部件成为自己的视图模型(注意,这是来自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);
            }
        });
    }
});

};

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