2013-02-11 47 views
1

我想分割我的視圖模型到多個可重複使用的視圖模型。 我有一個視圖模型,其中包含幾個下拉菜單和一個按鈕。訂閱從另一個視圖模型的值在淘汰賽js

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選擇的值從我MAINVIEW ??? 請幫忙!謝謝!

+0

你意識到你正在'TopView'構造函數中使用'self'而不事先將它分配給'this'? – 2013-02-11 17:29:19

回答

1

只要您不想完全交換,您不需要使其本身可觀察。你只可以創建它作爲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 example

+0

夥計。謝謝! – user1175857 2013-02-11 18:00:30