jquery
  • data-binding
  • knockout.js
  • 2010-12-28 9 views 0 likes 
    0

    私はメッセージのリストを作成しようとしていて、ko.observableArrayのように、未読カウントを自動的に更新します。ここに私がこれまで持っているものがあります。ビュー:observableArrayを設定する

    <p>Count <span data-bind="text: unreadCount()">&nbsp;</span></p> 
    <div data-bind='template: "conversationTemplate"'> </div> 
    <script type="text/html" id="conversationTemplate"> 
        <table> 
         <tbody> 
          {{each(i, conversation) converations()}} 
            <tr> 
             <td> 
              ${ i } 
             </td> 
             <td> 
              ${ status }, ${ title }, ${ project_name }, ${ preview } 
             </td> 
             <td> 
              Participants: 
              {{each(i, participant) participants}} 
                     ${ type } 
              {{/each}} 
             </td> 
            </tr> 
          {{/each}} 
         </tbody> 
        </table> 
    </script> 
    

    とビューモデル:

    $(function() { 
        var viewModel = { 
         converations: ko.observableArray([{ 
          status: "read", 
          title: "blah", 
          project_name: 'woopher', 
          preview: 'ding dong waaa', 
          participants: [{ 
           type: "Mobile" 
          }, { 
           type: "XXXXXX" 
          }] 
         }, { 
          status: "unread", 
          title: "Cha Ching", 
          project_name: 'Mint', 
          preview: 'Buy buy buy', 
          participants: [{ 
           type: "DADADADA" 
          }, { 
           type: "Home" 
          }] 
         }, { 
          status: "unread", 
          title: "Hevan", 
          project_name: 'LaLa', 
          preview: 'Apple Fan', 
          participants: [{ 
           type: "Mobile" 
          }, { 
           type: "XXXXXXXXXXXX" 
          }] 
         }]) 
        } 
        viewModel.unreadCount = ko.dependentObservable(function() { 
         return 2 
        }); 
        ko.applyBindings(viewModel); 
    }); 
    

    どのようにすることができますIコンピュータ「未読」状態との会話の合計数だろうunreadCount、?

    答えて

    2

    Dependent observables第2のパラメータを取ると、観察可能なプロパティがメソッドであるオブジェクトです。だから、最初にやるべきことはunreadCountは(viewModel)を確認する必要があることを、オブジェクトを追加します:

    viewModel.unreadCount = ko.dependentObservable(function() { 
         return 2 
    }, viewModel); // Added viewModel as the second parameter 
    

    次は、viewModel.conversationsをループにしたいと未読数を取得します。

    viewModel.unreadCount = ko.dependentObservable(function() { 
         /* 
         This function will be run every time an entry is 
         added or removed from `viewModel.conversations`. 
         It is *not* run when a conversation in the observableArray 
         is changed from "unread" to "read". 
         */ 
         var convs = this.conversations(); 
         var count = 0, i = 0, l = convs.length; 
         while (i < l) { 
          count += convs[i++].status === 'unread' ? 1 : 0; 
         } 
         return count; 
    }, viewModel); 
    
    関連する問題