Unable to enable visibility of item in observable array

44 views
Skip to first unread message

jk

unread,
Jun 18, 2015, 6:39:21 PM6/18/15
to knock...@googlegroups.com
In the code below, I have a list of 2 items. When the button is clicked it should enable for viewing the list items.
But KO doesn't pick up the change, even though the array is an observable, and so the list item does not show.
What is the reason for this behavior?


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="knockout-3.3.0.js"></script>
<style type="text/css">
    ul  
{   border: 1px solid black;
            list
-style-type: none;
       
}

</style>
</head>

<body>
<ul data-bind="foreach: { data: location }">
   
<li data-bind="text: $data.item, visible: $data.show"></li>
</ul>

<!--
<p>Search: <input id="myInput" data-bind="textInput: userName" /></p>
<p id="demo"></p>
-->


<div>
   
<button onclick="clicked()"> Click Me</button>
</div>

<script type="text/javascript">
 
var myViewModel = {
        location
: ko.observableArray([
           
{   item:'Apples',
                show
: true,
           
},
           
{   item:'Carrots',
                show
: true,
           
} ]),
   
};

 
function clicked() {
    myViewModel
.location()[0].show=true;
    myViewModel
.location()[1].show=true;

 
}

 myViewModel
.location()[0].show=false;

 ko
.applyBindings(myViewModel);
</script>
</body>
</html>

Noirabys

unread,
Jun 19, 2015, 2:21:35 AM6/19/15
to knock...@googlegroups.com
Hi,

knockout will be only aware of changes if you use observables:

<script type="text/javascript">
 var myViewModel = {
        location: ko.observableArray([
            {   item:'Apples',
                show: ko.observable(true),
            },
            {   item:'Carrots',
                show: ko.observable(true),
            } ]),
    };

 function clicked() {
    myViewModel.location()[0].show(true);
    myViewModel.location()[1].show(true);

 }

 myViewModel.location()[0].show(false);

 ko.applyBindings(myViewModel);
</script>

anyway i would not recommend to add gui related stuff to your model. 
keep that code in custom bindings.

greetings,
  noirabys

jk

unread,
Jul 10, 2015, 7:19:58 PM7/10/15
to knock...@googlegroups.com
Thanks. Got it.
Reply all
Reply to author
Forward
0 new messages