1

我正在尝试将我的视图模型拆分为多个可重用的视图模型。我有一个视图模型,其中包含几个下拉菜单和一个按钮。

    var TopView = function () {
       self.DropDownA = ko.observableArray();
       self.selectedDDA = ko.observable();
       self.DropDownB = ko.observableArray();
       self.selectedDDB = ko.observable();

       $.getJSON("someAPIurl", function (result) {
            ko.mapping.fromJS(result, {}, self);
        });  //this builds dropdownA

        $self.selectedDDA.subscribe(function(newValue) {
            $.getJSON("anotherAPI"+newValue, function (result) {
                ko.mapping.fromJS(result, {}, self);

            });
        };  // this builds dropdownB
        $self.buttonClicked = function() {
            alert("I clicked!");
        }
}

我的主视图模型如下所示:

var MainView = function () {
   var self = this;
   var topView = ko.observable({ TopView: new TopView() });

   // How do i get the selected values from topView once the user clicks the button???
}

如何从我的主视图订阅 DropDownA 和 DropDownB 选择的值???请帮忙!谢谢!

4

1 回答 1

1

TopView只要您不想完全交换它,就不需要使其本身可观察。您只需将其创建为的属性MainView并像在绑定中一样访问它:

<button data-bind="click:topView.buttonClicked">click me, I&#39;m a button!</button>

TopView保持原样(在您修复了使用self$self未定义它们之后)

MainView看起来像这样:

var MainView = function () {
   var self = this;
   self.topView = new TopView();
}

JSFiddle 示例

于 2013-02-11T17:38:35.220 回答