<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(),
要点1:这里twitterName是视图对象的一个属性,应用了Observable之后,它应该具备函数的功能。在赋值给其他变量时,需要写(),忘记带(),则会出现错误。
即如果写成这样则会出现错误,var name=self.twitterName,
{ 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 });
要点2:同要点1,注意赋值的方式,如果直接将一个对象赋给它,写成下面这样,则是错误的
self.resultData = { retrievalDate: new Date(), topTweets: simulatedResults };
}self.clearResults = function () {
self.resultData(undefined);
}
}
ko.applyBindings(new AppViewModel());