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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM