KnockoutJS 3.X API 第四章 数据绑定(4) 控制流with绑定

with绑定的目的

使用with绑定的格式为data-bind=”with:attribute”,使用with绑定会将其后所跟的属性看作一个新的上下文进行绑定。with绑定内部的所有元素将受到该上下文的约束。

当然,with绑定也可配合if或foreach绑定一起使用。

示例1

<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>

本例中,通过with直接绑定了coords监控属性,并在其内部直接调用了coords监控属性的内部属性。这里就体现了with绑定的特性。

示例2:一个互动的例子

Twitter account:   

Recent tweets fetched at

该例子中将使用with绑定动态添加和删除其绑定值为null/undefined或非null/undefined

UI源码:

<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>

视图模型源码:

function AppViewModel() {
    var self = this;
    self.twitterName = ko.observable('@example');
    self.resultData = ko.observable(); // No initial value
 
    self.getTweets = function() {
        var name = self.twitterName(),
            simulatedResults = [
                { text: name + ' What a nice day.' },
                { text: name + ' Building some cool apps.' },
                { text: name + ' Just saw a famous celebrity eating lard. Yum.' }
            ];
 
        self.resultData({ retrievalDate: new Date(), topTweets: simulatedResults });
    }
 
    self.clearResults = function() {
        self.resultData(undefined);
    }
}
 
ko.applyBindings(new AppViewModel());

 

备注:with的无容器绑定(虚拟绑定)

像if、foreach等的虚拟绑定一样,with绑定也一样。使用<!-- ko --><!-- /ko -->进行。

<ul>
    <li>Header element</li>
    <!-- ko with: outboundFlight -->
        ...
    <!-- /ko -->
    <!-- ko with: inboundFlight -->
        ...
    <!-- /ko -->
</ul>
posted @ 2016-10-06 10:37  SmallProgram  阅读(2000)  评论(0编辑  收藏  举报