[TOC]

入门

监控属性

使用内置绑定

控制文本和外观

绑定逻辑控制

处理表单属性

解析模板

高级应用

插件

更多信息

"with" 绑定

目的

with 绑定用来创建一个新的 绑定上下文,所以这样的后代元素绑定在一个指定的对象中。

The with binding creates a new binding context, so that descendant elements are bound in the context of a specified object.

当然, 你可以任意嵌套使用 with 绑定和其他的流程控制语句ifforeach

Of course, you can arbitrarily nest with bindings along with the other control-flow bindings such as if and foreach.

例 1

这是一个非常基本的例子绑定上下文到子对象。 请注意在子元素latitudelongitudedata-bind 属性中,不需要对象关系绑定前缀coords.,因为绑定上下文已经被切换到coords.元素中。

Here is a very basic example of switching the binding context to a child object. Notice that in the data-bind attributes, it is not necessary to prefix latitude or longitude with coords., because the binding context is switched to coords.

<h1 data-bind="text: city"> </h1>
<p data-bind="with: coords">
    Latitude: <span data-bind="text: latitude"> </span>,
    Longitude: <span data-bind="text: longitude"> </span>
</p>

<script type="text/javascript">
    ko.applyBindings({
        city: "London",
        coords: {
            latitude:  51.5001524,
            longitude: -0.1262362
        }
    });
</script>

例 2

用户交互演示:

  • with 绑定将动态的添加或删除子元素,取决关联的值是否为 nullundefined
  • 如果你想从父绑定上下文中访问数据或函数,你可以使用特定的上下文属性 $parentroot
  • The with binding will dynamically add or remove descendant elements depending on whether the associated value is null/undefined or not
  • If you want to access data/functions from parent binding contexts, you can use special context properties such as $parent and root.

尝试下:

Twitter account:

Recent tweets fetched at

源码: View

<form data-bind="submit: getTweets">
    Twitter account:
    <input data-bind="value: twitterName" />
    <button type="submit">Get tweets</button>
</form>

<div data-bind="with: resultData">
    <h3>Recent tweets fetched at <span data-bind="text: retrievalDate"> </span></h3>
    <ol data-bind="foreach: topTweets">
        <li data-bind="text: text"></li>
    </ol>

    <button data-bind="click: $parent.clearResults">Clear tweets</button>
</div>

源码: View model

function AppViewModel() {
    var self = this;
    self.twitterName = ko.observable('@StephenFry');
    self.resultData = ko.observable(); // No initial value

    self.getTweets = function() {
        twitterApi.getTweetsForUser(self.twitterName(), function(data) {
            self.resultData({
                retrievalDate: new Date(),
                topTweets: data.slice(0, 5)
            });
        });
    }

    self.clearResults = function() {
        self.resultData(undefined);
    }
}

ko.applyBindings(new AppViewModel());

参数

  • 主参数

绑定上下文您需要使用对象。

The object that you want to use as the context for binding descendant elements.

如果提供的表达式为 nullundefined,将不会绑定所包含的元素反而会从文档中删除。

If the expression you supply evaluates to null or undefined, descendant elements will not be bound at all, but will instead be removed from the document.

如果提供的表达式包含任何 observable 值,observables 的每次更新都会重置区域绑定。旧的元素将被绑定清除,新的标记和绑定将被重新添加到上下文中。

If the expression you supply involves any observable values, the expression will be re-evaluated whenever any of those observables change. Then, descendant elements will be cleared out, and a new copy of the markup will be added to your document and bound in the context of the new evaluation result.

  • 附加参数

注 1: 在没有容器元素的情况下使用 “with”

ifforeach绑定一样,with 可以在没有父级容器的情况下使用。如果要在不能引入一个新的容器元素的情况下使用 with 绑定这很重要。 请参考 ifforeach 文档来查看更多信息。

Just like other control flow elements such as if and foreach, you can use with without any container element to host it. This is useful if you need to use with in a place where it would not be legal to introduce a new container element just to hold the with binding. See the documentation for if or foreach for more details.

例子:

<ul>
    <li>Header element</li>
    <!-- ko with: outboundFlight -->
        ...
    <!-- /ko -->
    <!-- ko with: inboundFlight -->
        ...
    <!-- /ko -->
</ul>

注释作为开始/结束的标记,定义一个 “虚拟元素” 作为容器包裹在内。Knockout 将会应用此方法的绑定。

The and comments act as start/end markers, defining a “virtual element” that contains the markup inside. Knockout understands this virtual element syntax and binds as if you had a real container element.

依赖性

除KO核心类库外,无依赖。

(c) knockoutjs.com