此问题基于 Knockout 在线教程第 2 步中的代码:http://learn.knockoutjs.com/#/?tutorial=webmail
以这个 jsfiddle 为例:http://jsfiddle.net/rniemeyer/PKDdG/
第 10 行到第 12 行当前使用 with
Knockout 绑定(bind):
<table class="mails" data-bind="with: chosenFolderData">
<thead><tr><th>From</th><th>To</th><th>Subject</th><th>Date</th></tr></thead>
<tbody data-bind="foreach: mails">
教程解释:
The with binding creates a binding context that will be used when binding any elements inside it. In this example, everything inside the will be bound to chosenFolderData, so it's not necessary to use chosenFolderData. as a prefix before mails.
我尝试将第 10 行到第 12 行替换为以下内容,基于对上面引用的测试:
<table class="mails">
<thead><tr><th>From</th><th>To</th><th>Subject</th><th>Date</th></tr></thead>
<tbody data-bind="foreach: chosenFolderData().mails">
而且我在控制台中收到一个 Cannot read property 'Inbox' of undefined
错误。
在教程中,为什么代码工作需要 with
绑定(bind)?我知道它正在改变绑定(bind)概念,但为什么我不能手动选择带有 chosenFolderData.
前缀的绑定(bind)上下文?
最佳答案
with
绑定(bind)发生的事情是,如果您与 with
绑定(bind)的属性为 null 或未定义,它将跳过内部的绑定(bind)(它实际上不会' t 渲染那些元素)。当您删除 with
时,它会在未定义时尝试绑定(bind) chosenFolderData
,因此所有内部属性绑定(bind)都会失败。一旦遇到错误,knockout 就会停止尝试绑定(bind)模型的其余部分。
您可以使用 if
绑定(bind)获得相同的结果:
<table class="mails" data-bind="if: chosenFolderData">
<thead><tr><th>From</th><th>To</th><th>Subject</th><th>Date</th></tr></thead>
<tbody data-bind="foreach: chosenFolderData().mails">
因为 if
绑定(bind)会给您类似的结果。参见 http://jsfiddle.net/PKDdG/166/
with
是一种便利,可以让您不必继续放置长链的属性访问。
docs 中提到了这一点,但它可能并不像它应该的那样清晰和明显:
The with binding will dynamically add or remove descendant elements depending on whether the associated value is null/undefined or not
关于javascript - 为什么在使用 Ajax 请求时需要 Knockout 'with' 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22994075/