2012-10-26 58 views
5

另一個敲除問題,我似乎無法找到幫助。敲除手動訂閱不會觸發下拉更改

我基本上是試圖實現級聯下拉。前些天我請求幫助解決我複雜的JSON(這是來自CakePHP控制器的。我前些天收到的幫助非常好,但我遇到了另一個小問題。

我遇到的問題是我在調用JSON來獲取國家列表後,我更新了viewModel,一旦我填充下拉列表,我希望顯示縣的列表,並最終顯示一個城市列表,但我還沒有到那裏。不幸的是,當我改變我從列表中選擇一個國家,我的observable不會觸發,我懷疑這是因爲我創建了this.selectedCountry = ko.observable()並使用映射進行更新,但我不知道這是一個什麼有效的選項。當然,我也可以成爲該標記:/

我有以下代碼

HTML:

<select id="countries" 
      data-bind=' 
       options: countries, 
       optionsValue : "Id", 
       optionsText: "country", 
       optionsCaption: "[Please select a country]", 
       value: selectedCountry'> 
</select> 

<select id="counties" 
       data-bind=' 
        options: selectedCountry() ? counties : null, 
        optionsValue : "Id", 
        optionsText: "County", 
        optionsCaption: "[Please select a county]", 
        value: selectedCounty, 
        visible: (counties() && counties().length > 0)'> 
     </select> 

的Javascript

var countryData= {"countries":[{"Country":{"id":"1","country":"England"}},{"Country":{"id":"2","country":"Wales\/Cymru"}},{"Country":{"id":"3","country":"Scotland"}},{"Country":{"id":"4","country":"Republic of Ireland"}},{"Country":{"id":"5","country":"Northern Ireland"}}]}; 

var countyData= {"country":[{"County":{"id":"1","county":"Essex"}}]}; 

var countryMappingOptions = { 
    'countries': { 
     'update': function (options) { 
      return ko.mapping.fromJS(options.data.Country); 
     }, 
     'ignore': ["selectedCountry"] 
    } 
}; 

var countyMappingOptions = { 
    'counties': { 
     'update': function (options) { 
      return ko.mapping.fromJS(options.data.County); 
     } 
    } 
}; 
     var vm= function() { 
      this.selectedCountry = ko.observable(); 
      this.selectedCounty = ko.observable(); 
      this.countries = ko.mapping.fromJS([]); 
      this.counties = ko.mapping.fromJS([]); 
      // Whenever the continent changes, reset the country selection 
      this.selectedCountry.subscribe(function (countryId) { 
       alert(countryId); 
       this.selectedCounty(undefined); 
       this.counties(undefined); 
       if (countryId != null) { 
        ko.mapping.fromJS(countyData, countyMappingOptions,this.viewModel); 
       } 
      }); 
      this.selectedCounty.subscribe(function (countryId) { 
       alert(countryId);  
      } .bind(this)); 
     }; 

     var viewModel = new vm(); 
     ko.applyBindings(viewModel); 
     console.log(viewModel .countries()); 
     ko.mapping.fromJS(countryData, countryMappingOptions ,viewModel); 
     console.log(viewModel .selectedCountry()); 

我還創建了一個的jsfiddle演示這裏的問題http://jsfiddle.net/jbrr5/21/

再次與這個問題的任何幫助將不勝感激,一旦我得到淘汰賽的一竅不通吧。

感謝

回答

6

的一些問題:

  • 你忘了做.bind(this)第一訂閱
  • this.viewModel,而不是僅僅this
  • 你有optionsValue: "Id",而不是optionsValue: "id"
  • 你有optionsText: "County"而不是optionsText: "county"
  • countyData的數組被稱爲的country代替counties

更新小提琴:http://jsfiddle.net/antishok/jbrr5/23/

+0

非常感謝你,我多麼懷念這些錯誤,我永遠也不會知道!欣賞迴應。 – user1771329

相關問題