Reputation: 1303
I've a problem with Knockout.JS
when I try to set the visibility of a button depending on an specific object property from a observableArray
. The object binded to my view is this one:
function IncomeDeclarationHub() {
var self = this;
//Other properties
self.IncomeDeclarationViewModel = ko.observableArray();
}
And of course this is the object used to fill that observableArray
:
function IncomeDeclarationViewModel(data) {
var self = this;
//Other properties
self.IsSent = ko.observable(data.IsSent);
}
At some point I fill IncomeDeclarationViewModel
with data, and it works fine. The thing is that I need to show a button only if the property IsSent
from the first element of said observableArray
is true. So I tried many things like:
<input type="image" data-bind="visible: IncomeDeclarationViewModel()[0].IsSent()" />
Also changing where I make the reference for visible: IncomeDeclarationViewModel[0].IsSent()
or visible: IncomeDeclarationViewModel()[0].IsSent
.
But I keep getting this error:
Uncaught Error: Unable to parse bindings.
Message: TypeError: Cannot read property 'IsSent' of undefined;
Bindings value: click: Print, visible: myIncomeDeclarationViewModel()[0].IsSent()
What I'm missing or where I'm wrong?
Upvotes: 0
Views: 208
Reputation: 7958
I think this is because at some point IncomeDeclarationViewModel isn't populated which causes the error as there will be no object in the first element if the array is empty.
Change the binding to this to check if there are elements in the array:
<input type="image" data-bind="visible: IncomeDeclarationViewModel().length > 0 && IncomeDeclarationViewModel()[0].IsSent()" />
An alternative to this is to use the with binding which any children bindings will only display and execute if there is an object in the first item of IncomeDeclarationViewModel:
<div data-bind="with: IncomeDeclarationViewModel()[0]">
<input type="image" data-bind="visible: IsSent" />
</div>
Upvotes: 1