javascript - 为什么在使用 Ajax 请求时需要 Knockout 'with' 绑定(bind)

标签 javascript data-binding knockout.js

此问题基于 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/

相关文章:

javascript - 仅当用户更改时才将值更新到数据库,或者如果代码更改值则暂停某些订阅

javascript - 恼人和奇怪的正则表达式问题 : 'io\.' get's a match on the word 'function'

javascript - 纯 JavaScript 等价于 jquery Replace()

html - 剑道网格,数据列中的模板不起作用

c# - 在运行时获取 C# 中属性的字符串表示形式

android - Kotlin-DataBinding-错误 : Check your module classpath for missing or conflicting dependencies

javascript - 不为自托管 chrome 扩展的 chrome.identity.getAuthToken 调用回调

javascript - z 索引为 : 9999 being hidden by iframe with z-index: -1 IE8- 的 Div

javascript - 包含对象数组的 typescript 文字对象

knockout.js - 查找嵌套的 foreach 索引号