Knockoutjs: hide image when emty or null

Attisppiomo

New Member
I'm trying to implement knockoutjs for the first time in a web page. I stumbled into the following problem, but maybe it is also a case of "best practices".I have a product page, and a product can have a product image. When there is no product image available, the property is set to null and I need to show a "no image available" picture.My model:\[code\]function ProductOverview() { var self = this; self.guid = ko.observable(); self.Image = ko.observable(); self.IsActive = ko.observable(false);}\[/code\]My viewmodel:\[code\]function productOverviewModelView() {var self = this;self.productOverview = new ProductOverview();self.ShowNoImage = ko.computed(function () { if (self.productOverview.Image() === null || self.productOverview.Image() === "") { return true; } else { return false; }}, this);self.ImageAvailable = ko.computed(function () { if (self.productOverview.Image() === null || self.productOverview.Image === "") { return false; } else { return true; }}, this);//whenever the device is changed call this functionself.selectedProduct.subscribe(function () { if (self.selectedProduct === "") { self.productOverview = null; } else { $.ajax({ type: "POST", url: "productoverview.aspx/getdevice", data: "{'guid':'" + self.selectedProduct() + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { var product = JSON.parse(unescape(data.d)); self.productOverview.guid(product.guid); self.productOverview.Image(product.Image); self.productOverview.IsActive(product.IsActive); } }); }});\[/code\]}My view:\[code\]<div style="display:inline-block;"> <img alt="" src="http://stackoverflow.com/questions/15814506/#" data-bind="attr: { src: productOverview.Image }" /> <img alt="" src="http://stackoverflow.com/images/no-image-available.jpg" data-bind="visible:ShowNoImage" /></div>\[/code\]It works, but like this it is not working:\[code\]<img alt="" src="http://stackoverflow.com/images/no-image-available.jpg" data-bind="visible: productOverview.Image != ''" />\[/code\]Is there a shorter way, instead of making the computed observables?I also wanted to show an active image when the product is active:\[code\]<img src="http://stackoverflow.com/images/active_icon.gif" data-bind="visible: productOverview.isActive" />\[/code\]But this image is not showing, why?And the other way around, can I also show the inactive image like this?\[code\]<img src="http://stackoverflow.com/images/notactive_icon.gif" data-bind="visible: !productOverview.isActive" />\[/code\]
 
Top