2012-08-14 122 views
0

好吧,在我展示我的代碼之前,我的方法讓我解釋手頭的問題是什麼,也許有人有更好的解決方案。問題是我有一個數組按特定標準分組的列表。我需要爲每個條件呈現一個列表/部分,並且每個部分都包含一個也應該呈現爲HTML的對象列表。KnockoutJS嵌套的模板綁定

我是KnockoutJS的新手 - 我昨天開始使用它。但鑑於眼前的問題,我搜索了文檔中的可觀察字典或類似的東西。幸運的是,我找到了ko.observableDictionary plugin。所以,我想這應該做的伎倆,並寫了下面的代碼(只是一些概念驗證):

<div id="tiles-holder" data-bind="template: { name: 'tile-list', foreach: dictionary }"> 

</div> 

<script type="text/html" id="tile-list"> 
<div class="md-auto-max-width"> 
    <div class="md-list-tiles md-auto-arrange-tiles" data-bind="template: { name: 'tile-default', foreach: items }"></div> 
</div> 
</script> 

<script type="text/html" id="tile-default"> 
    <div class="metro-tile-square md-list-item md-list-tile-large"> 
     <div class="md-list-item-image" data-bind="css: { defaultimage: $data.title() != 'architect' }"></div> 

     <div> 
      <span data-bind="text: name"></span> - <span data-bind="text: $data.department"></span> 
     </div> 

    </div> 
</script> 

<script type="text/javascript" src="@Url.Content("~/Scripts/metro/ko.observableDictionary.js")"></script> 
<script type="text/javascript"> 

    $(function() { 
     var viewModel = function TileViewModel() { 
      var self = this; 

      self.dictionary = new ko.observableDictionary(); 

      for (var i = 0; i < 15; i++) { 
       self.dictionary.push("Developers", new employee('developer' + i, 'developer', 'projectDevelopment')); 
       self.dictionary.push("Analysts", new employee('analyst' + i, 'analyst', 'business intelligence')); 
      } 
      self.dictionary.push("Architects",new employee('Some Architect', 'architect', 'Architecture and development')); 



      function employee(name, title, department) { 
       this.name = ko.observable(name); 
       this.title = ko.observable(title); 
       this.department = ko.observable(department); 
      } 
     }; 

     ko.applyBindings(new viewModel(), $('#tiles-holder').get(0)); 
    }); 
</script> 

但我不斷收到以下錯誤:

Error: Unable to parse bindings. Message: TypeError: $data.title is not a function; Bindings value: css: { defaultimage: $data.title() != 'architect' }

我相信問題是$data不涉及模板的數據上下文。但我該如何解決這個問題?

回答

1

使用字典擺在首位,爲什麼,你不使用它作爲一個字典,以便使用observableArray代替

無論如何,你需要訪問的每個項目

http://jsfiddle.net/X2xZM/

的價值主張