我想,对于淘汰赛的专家,这将是一个简单的问题,对我来说这是令人困惑的。
我的JSON输入:
{
"odata.metadata":"http://localhost:49163/odata/$metadata#TwitterMessages","value":[
{
"message":{
"text":"Pellentesque fermentum a diam a suscipit. Donec ultrices tempor sapien, vitae dictum erat pulvinar sagittis. Vivamus a fermentum lectus, et lacinia enim. Morbi pretium adipiscing risus, vitae euismod lacus fermentum eu.","company_fk":3,"image_url":"http://www.baconwrappedmedia.com/wp-content/uploads/2013/01/funny-kids-bacon-wrapped-media-21.jpg","active":true,"author_id":"3242342423","message_id":3,"author_picture":"http://3.bp.blogspot.com/_Gxh8CVH8l8Y/TJBDI4QVfnI/AAAAAAAAAWE/W1H4Z2MAub0/s1600/547206_1271901770610.27res_400_483.jpg","author_name":"Ligula","source":"TWITTER","createddatefriendly":"1 day ago","message":"Ut at erat at mauris euismod tincidunt non id justo?","pubdate":"2014-01-10T13:27:42.917"
},"hashtag":{
"hashtag_id":2,"hashtag":"#voetbal","company_fk":3
},"twitter_id":"0","user_screenname":"Ligula","user_name":"Ligula","message_fk":3,"hashtag_fk":2
},{
"message":{
"text":"Duis sed nunc semper, volutpat urna et, volutpat diam.","company_fk":3,"image_url":"http://www.allfunnystuff.com/wp-content/uploads/2013/04/funny-baby-angry-punch.jpg","active":true,"author_id":"75675675","message_id":4,"author_picture":"http://www.drodd.com/images8/funny-face15.jpeg","author_name":"Curabitur","source":"TWITTER","createddatefriendly":"3 day(s) ago","message":"Suspendisse a sapien id lorem tincidunt imperdiet eget id velit.","pubdate":"2014-01-10T13:30:26.657"
},"hashtag":{
"hashtag_id":2,"hashtag":"#voetbal","company_fk":3
},"twitter_id":"0","user_screenname":"Curabitur","user_name":"Curabitur","message_fk":4,"hashtag_fk":2
}
]
}
我的JavaScript /淘汰赛代码:
function CompanyViewModel() {
var self = this;
self.name = ko.observable();
}
function TweetViewModel(item) {
var self = this;
self.user_screenname = ko.observable("");
self.user_name = ko.observable("");
self.message = ko.observable("");
self.hashtag = ko.observable("");
ko.mapping.fromJS(item, {}, self);
}
function ViewModel() {
var self = this;
self.Company = ko.observable(new CompanyViewModel());
self.Tweets = ko.observableArray([new TweetViewModel()]);
$.getJSON('/Data/company.json', function (data) {
ko.mapping.fromJS(data, {}, self.Company());
});
$.getJSON('/Data/tweets.json', function (allData) {
var mappedTweets = $.map(allData.value, function (item) {
return new TweetViewModel(item)
});
self.Tweets(mappedTweets);
console.log(self.Tweets())
});
}
var vm = new ViewModel();
ko.applyBindings(vm);
我的HTML:
<tbody data-bind="foreach: Tweets">
<tr>
<td data-bind="text: user_screenname"></td>
<td data-bind="text: message().text"></td>
<td data-bind="text: hashtag().hashtag"></td>
</tr>
</tbody>
一切工作正常。 但这里是我的问题:
我为什么不需要“声明”可观察到使用数据绑定的Message.Text但我确实需要声明user_screenname观察到的?
如果我想删除行:
self.user_screenname = ko.observable("");
我得到一个错误:user_screenname没有定义。 因为我用的映射建设我预计user_screenname属性也自动映射到视图模型。 还是我做错了什么?