I've got a very simple View Model:
var ViewModel = function() {
this.showRow = ko.observable(false);
this.toggleVisibility = function() {
if(this.showRow == true){
this.showRow = false;
}
else{
this.showRow = true;
}
alert('showRow is now '+this.showRow); //only here for testing
};
};
with equally simple markup:
<a href="#" data-bind="click: toggleVisibility">Toggle</a>
<br />
<table>
<tr data-bind="visible: showRow">Some Text</tr>
</table>
My problem is, that when the link is clicked, the alert box shows (displaying the correct value - true/false)
However, the visible binding on the tr
element doesn't seem to work - either initially (the row should be invisible on load) nor when the value of showRow
toggles.
jsFiddle of above- http://jsfiddle.net/alexjamesbrown/FgVxY/3/
To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.
The visible binding shows or hides the target DOM element or widget depending on the View-Model value. If the value is true , the target DOM element is shown. If the value is false , the target DOM element is hidden—its display CSS attribute is set to none .
The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.
Whenever you declare a computed observable, KO immediately invokes its evaluator function to get its initial value. While the evaluator function is running, KO sets up a subscription to any observables (including other computed observables) that the evaluator reads.
You need to modify your html as follows:
<table>
<tr data-bind="visible: showRow"><td>Some Text</td></tr>
</table>
And JavaScript as follows:
var ViewModel = function() {
var self = this;
self.showRow = ko.observable(false);
self.toggleVisibility = function() {
self.showRow(!self.showRow());
alert('showRow is now ' + self.showRow());
};
};
ko.applyBindings(new ViewModel());
Syntax to set the value to observable property is: self.showRow(value);
If need to have tags inside of tags.
I've also modified your fiddle to simplify the javascript and follow newer code practices with regard to "this". See http://jsfiddle.net/FgVxY/4/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With