Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout visible binding not working

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/

like image 613
Alex Avatar asked Nov 26 '12 18:11

Alex


People also ask

How do you activate Knockout?

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.

What happens in visible binding?

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 .

What is $data in Knockout?

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.

How does Ko computed work?

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.


1 Answers

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/

like image 86
photo_tom Avatar answered Oct 19 '22 19:10

photo_tom