2013-02-10 70 views
1

我已經使用Knockout創建了一個非常簡單的數據加載示例。我想要做的是在數據加載時添加一個加載圖標以顯示。任何人都可以告訴我正確的語法用於下面的示例嗎?向Knockout添加加載圖標javascript

<script type="text/javascript" src="@Url.Content("~/Scripts/knockout-2.1.0.js")"></script> 
<script type="text/javascript"> 

    function QBRatingsViewModel() { 
      var self = this; 
      var baseUri = '@ViewBag.ApiUrl'; 
      self.qbratings = ko.observableArray(); 

      $.getJSON("/api/qbrating", self.qbratings); 
    } 

    $(document).ready(function() { 
     ko.applyBindings(new QBRatingsViewModel()); 
    }); 

    </script> 

     <div class="page" id="page-index"> 
    <div class="page-region"> 
     <div class="page-region-content"> 
      <div class="grid"> 
       <div class="row"> 
        <div class="span4"> 
            <h3>QB Ratings (up to week 12)</h3> 
            <div id="divLoading"> 
             <table class="bordered"> 
              <thead> 
               <tr style="background-color:#f1f1f1"> 
                <td>Team</td> 
                <td>Comp %</td> 
                <td>Av Gain</td> 
                <td>TD %</td> 
                <td>Int %</td> 
                <td>Rating</td> 
               </tr> 
              </thead> 
              <tbody data-bind="foreach: qbratings"> 
               <tr class="qbrating"> 
                <td><span data-bind="text: $data.TeamName"></span></td> 
                <td><span data-bind="text: $data.Completion"></span></td> 
                <td><span data-bind="text: $data.Gain"></span></td> 
                <td><span data-bind="text: $data.Touchdown"></span></td> 
                <td><span data-bind="text: $data.Interception"></span></td> 
                <td><span data-bind="text: $data.CalculatedRating"></span></td> 
               </tr> 
              </tbody> 
             </table> 
            </div> 
           </div> 
          </div> 
         </div> 
        </div> 
       </div> 
      </div> 

回答

17

雖然這不是特別的例子,這是你可以用它來顯示任何類型的負載指標的技術:

http://jsfiddle.net/wiredprairie/Uq8VJ/

的重要組成部分,是隻將狀態切換在您的視圖模型中可觀察的,然後可以觸發可見性綁定來隱藏或顯示加載指示器。

var vm = { 
    isLoading: ko.observable(false), 
    loadData: function() { 
     var self = this; 
     self.isLoading(true); 
     $.getJSON("/echo/json?json={}&delay=2") 
      .success(function() { 
      // success! 
     }) 
      .complete(function() { 
       // always remove the loading, regardless of load/failure 
      self.isLoading(false); 
     }); 
    } 
}; 

ko.applyBindings(vm); 

和HTML:

<div id='container'> 
    <div>always showing</div> 
    <div id='loading' data-bind="visible: isLoading">Loading...</div> 
</div> 
<div> 
    <button data-bind="click: loadData">Simulate Load</div> 
</div>