2013-03-21 72 views
0

這篇文章是one的後續文章。淘汰賽遞歸映射問題

的後跟我已經更新了代碼:

viewModel.getQuotesSuccess = function (result) { 

    var myCoverQuotesViewModel = function (data) { 
    var self = this; 
    ko.mapping.fromJS(data, {}, self); 

    self.Childs = ko.observableArray(ko.utils.arrayMap(data.Childs, function (c) { 
     return new myCoverQuotesViewModel(c); 
    })); 

    self.selectedChild = ko.observable(); 
    self.showChildren = ko.computed(function() { 
     return self.selectedChild() 
     && self.selectedChild().Childs().length > 0; 
    }); 



var mapping = { 
    'CoverQuotes': { 
     create: function (options) { 
      return new myCoverQuotesViewModel(options.data); 
     } 
    } 
} 

ko.mapping.fromJS(result, mapping, viewModel); 

};

視圖模型會是這個樣子:

var viewModel = { 

    CoverQuotes: [{id: 1, label:'test', Childs:[{id: 2, label:'child1'}]] 
}; 

所以,總之,我有CoverQuotes的數組,其中每個元素還包含CoverQuotes(依此類推)的數組。

我在這個映射中遇到的問題是使用Childs可觀察數組。當撥打電話:

return new myCoverQuotesViewModel(options.data); 

爲主要對象,它工作正常。但是,在從arrayMap函數內調用構造函數時,則該行:

ko.mapping.fromJS(data, {}, self); 

不會做任何事情。

因此,嵌套的孩子被分配屬性selectedChild和showChildren,但他們缺少所有其他人(如本例中的id和label)。

我錯過了什麼,所以映射也適用於兒童?

回答

0

我使用遞歸定義映射

viewModel.getQuotesSuccess = function (result) { 
    var myCoverQuotesViewModel = function (data) { 
     var self = this; 

     var mappingChildren = { 
      'Childs': { 
       create: function (options) { 
        return new myCoverQuotesViewModel(options.data); 
       } 
      } 
     } 

     ko.mapping.fromJS(data, mappingChildren, self); 


     self.selectedChild = ko.observable(); 
     self.showChildren = ko.computed(function() { 
      return self.selectedChild() && self.selectedChild().Childs().length > 0; 
     }); 

     self.IsVisible = ko.computed({ 
      read: function() { 
       var visible = true; 
       if (self.DependsOn().length > 0) { 
        $.each(self.DependsOn(), function (index, value) { 
         var dependency = viewModel.QuoteSelectedViewModel().CoverQuotes.filterByProperty("Code", value); 
         if (dependency().length > 0) { 
          visible = visible & dependency()[0].IsSelected(); 
         } else { 
          visible = false; 
         } 
        }); 
       } 

       return visible; 
      }, 
      deferEvaluation: true 
     }, this); 
    } 

    var mapping = { 
     'CoverQuotes': { 
      create: function (options) { 
       return new myCoverQuotesViewModel(options.data); 
      } 
     } 
    } 

    ko.mapping.fromJS(result, mapping, viewModel); 
}; 
+0

你豈不放置你的mappingChildren選擇你的虛擬機之外實現同樣的目標解決我的問題?實際上,您應該能夠將mappingChildren的'Childs'屬性複製到映射中,並將子映射指令複製到ko.mapping.fromJS(data,mapping,self)。由於數據包含'Childs'屬性,映射應該使用'Childs'屬性,即使映射是相同的。 – beauXjames 2013-11-01 21:19:47