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:一個互動的例子

該例子中將使用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>
以上所述是小編給大家介紹的KnockoutJS 3.X API 第四章之數據控制流with綁定,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對網站的支持!