KnockoutJS - with 绑定

此绑定用于在指定对象的上下文中绑定对象的子元素。此绑定还可以与其他类型的绑定嵌套,例如 if 和 foreach。

语法

with: <binding-object>

参数

  • 将要用作绑定子元素上下文的对象作为参数传递。如果传递的对象或表达式被评估为 null 或未定义,则不会显示子元素。

  • 如果提供的参数是可观察的,则将重新评估表达式。相应地,子元素将根据刷新后的上下文结果重新处理。

示例

我们来看下面的示例,演示了 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 文件。

观察

无容器

可能存在无法将数据绑定放置在 DOM 元素内的情况。基本绑定仍可在基于注释标记的 无容器 语法的帮助下执行,如下面的代码所示。

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

<!--ko--> 和 <!--/ko--> 作为开始和结束标记,使其成为虚拟语法,并且像真实容器一样绑定数据。

knockoutjs_declarative_bindings.html