with绑定的目的
使用with绑定的格式为data-bind=”with:attribute”,使用with绑定会将其后所跟的属性看作一个新的上下文进行绑定。with绑定内部的所有元素将受到该上下文的约束。
当然,with绑定也可配合if或foreach绑定一起使用。
示例1
Latitude: , Longitude:
本例中,通过with直接绑定了coords监控属性,并在其内部直接调用了coords监控属性的内部属性。这里就体现了with绑定的特性。
示例2:一个互动的例子
该例子中将使用with绑定动态添加和删除其绑定值为null/undefined或非null/undefined
UI源码:
Recent tweets fetched at
视图模型源码:
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绑定也一样。使用和进行。
- Header element ... ...
以上所述是小编给大家介绍的KnockoutJS 3.X API 第四章之数据控制流with绑定,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!



