我想檢查'類型'綁定,如果他等於某個字符串,但看起來他沒有執行它。Knockout.js如果語句問題
我的HTML頁面:
<div class="socialWrapper" data-bind="foreach: facebookposts">
<!-- ko if: {Type()==='link'}-->
<img data-bind='attr: { src: FromPicture }'/>
<p data-bind="text:From"></p>
<!-- /ko -->
</div>
當我剛剛返回:
<p data-bind="text: Type"></p>
我的輸出= 「字符串」
正如你可以看到我想要得到基於正確觀測if語句。 視圖模型:
function Post(allData) {
var profileImageUrl = "http://graph.facebook.com/" + allData.from.id + "/picture?type=large";
this.Type = ko.observable(allData.type);
this.From = ko.observable(allData.from.name);
this.FromPicture = ko.observable(profileImageUrl);
this.Created = ko.observable(allData.created_time);
this.Comments = ko.observable(allData.comments.count);
this.Message = "";
this.Likes = "";
this.LinkImage = "";
this.LinkUrl = "";
this.LinkName = "";
this.LinkTitle = "";
this.LinkDescription = "";
this.Story = "";
this.Photo = "";
this.PhotoDescription = "";
if (allData.type === 'status') {
this.Message = ko.observable(allData.message);
this.Likes = ko.observable(allData.likes);
}
if (allData.type === 'link') {
this.Message = ko.observable(allData.message);
this.LinkImage = ko.observable(allData.picture);
this.LinkUrl = ko.observable(allData.link);
this.LinkName = ko.observable(allData.name);
this.LinkTitle = ko.observable(allData.caption);
this.LinkDescription = ko.observable(allData.description);
this.Likes = ko.observable(allData.likes);
}
if (allData.type === 'photo') {
this.Story = ko.observable(allData.story);
this.Photo = ko.observable(allData.picture);
this.PhotoDescription = ko.observable(allData.description);
}
}
var masterViewModel = {
facebookposts: ko.observableArray([]),
getFacebookObjects: function() {
var getUrl = '/api/[email protected]["fb_access_token"]';
$.ajax({
url: getUrl,
type: 'GET',
dataType: 'json',
success: function (allData) {
var mappedPosts = $.map(allData, function (item) {
return new Post(item);
});
masterViewModel.facebookposts(mappedPosts);
},
statuscode: {
401: function() {
console.log("Not Authorized");
}
}
});
}
};
$(document).ready(function() {
ko.applyBindings(masterViewModel);
masterViewModel.getFacebookObjects();
});
任何人有關於if語句如何解決這一問題的想法?
如果不工作,你的意思是它似乎始終評估爲真?總是假?或者它給你一些錯誤? – 2012-04-26 14:09:10
另外,試試Type()==='link'。可觀察對象實際上是函數,您需要使用括號來調用函數並實際獲取值。 – 2012-04-26 14:10:16
@Matt Burland:它總是評估爲false,並且Type()==='link'不起作用。 – 2012-04-26 14:12:30