我如何使用knockoutjs动态控件

时间:2012-06-25 11:07:11

标签: javascript knockout.js

我有一个场景,我试图应用淘汰赛来解决一些问题。基本上我有这种ui

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

我认为每一行都是数组中的另一个Widget,所以我的淘汰是为了简单

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,

&GT;     

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

干杯!

1 个答案:

答案 0 :(得分:0)

这样做的一种方法是让每个小部件都有自己的viewmodel(注意,这是来自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);
            }
        });
    }
});

};

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