- Knockout.JS 教程
- Knockout.JS - 首页
- Knockout.JS - 概述
- Knockout.JS - 环境设置
- Knockout.JS - 应用
- Knockout.JS - MVVM 框架
- Knockout.JS - 可观察值
- 计算可观察值
- Knockout.JS - 声明性绑定
- Knockout.JS - 依赖关系跟踪
- Knockout.JS - 模板化
- Knockout.JS - 组件
- Knockout.JS 资源
- Knockout.JS - 快速指南
- Knockout.JS - 资源
- Knockout.JS - 讨论
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
广告