KnockoutJS - with 繫結



此繫結用於繫結指定物件上下文中物件子元素。此繫結還可以與其他型別的繫結(如和)巢狀。

語法

with: <binding-object>

引數

  • 將希望用作繫結子元素上下文的物件作為引數傳遞。如果透過的表示式或物件評估為 null 或 undefined,則不會顯示子元素。

  • 如果所提供的引數是可觀察值物件,則將重新評估該表示式。相應地,將根據重新整理的上下文結果來重新處理子元素。

示例

讓我們看看以下演示使用 with 繫結的示例。

<!DOCTYPE html>
   <head>
      <title>KnockoutJS with binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
         type = "text/javascript"></script>
   </head>
   
   <body>
      <h1 data-bind = "text: siteName"> </h1>
      
      <table border = "1">
         <thead>
            <th>Course Name</th><th>Fees</th><th> Start Date</th>
         </thead>
         
         <tbody data-bind = "with: courses ">
            <tr>
               <td><span data-bind = "text: courseName"></span></td>
               <td><span data-bind = "text: Fees"></span></td>
               <td><span data-bind = "text: startDate"> </span></td>
            </tr>
         </tbody>
      </table>

      <script type="text/javascript">
         function AppViewModel() {
            self = this;
            self.siteName = ko.observable( 'TutorialsPoint');
            self.courses = ko.observable ({
               courseName:  'Microsoft .Net', 
               Fees: 20000, startDate: '20-Mar-2016'
            });
         };
         
         var vm = new AppViewModel();
         ko.applyBindings(vm);
      </script>
      
   </body>
</html>

輸出

讓我們執行以下步驟,瞭解上述程式碼如何工作:

  • 將上述程式碼儲存在 **with-bind.htm** 檔案中。

  • 在瀏覽器中開啟此 HTML 檔案。

觀察

無容器 with

有時,無法將資料繫結放在 DOM 元素內。下文中所示,基於註釋標記的 **無容器** 語法仍然可以使用來執行必要的繫結。

<ul>
   <li>Course Info</li>
   <!-- ko with: currentClasses -->
      ...
   <!-- /ko -->
   <!-- ko with: plannedClasses -->
      ...
   <!-- /ko -->
</ul>

<!--ko--> 並且 <!--/ko-->用作開始和結束標記,使其成為虛擬語法,並且繫結資料就像它是真實容器一樣。

knockoutjs_declarative_bindings.htm
廣告
© . All rights reserved.