Reputation: 325
I know that $data variable provides access to the current object your context is in. Also I can use foreach binding and add property name to the books object.
This code iterate over the array named books and result are displayed in the DOM as list of items.
But why if I change that array name from books to any other name it does not display items.
<!DOCTYPE html>
<html>
<head>
<title>Data Binding with KnockoutJS</title>
</head>
<body>
<ul >
<!-- ko foreach: books -->
<li data-bind="text: $data"></li>
<!-- /ko -->
</ul>
<script type='text/javascript' src='knockout-3.4.2.js'></script>
<script>
var ViewModel = function() {
var self = this;
self.books = [
'Journy to the earth',
'effective study plans'
];
};
var myModel = new ViewModel();
ko.applyBindings(myModel);
</script>
</body>
</html>
Here is the code after changing array name to titles and cause error.
<!DOCTYPE html>
<html>
<head>
<title>Data Binding with KnockoutJS</title>
</head>
<body>
<ul >
<li data-bind="text: $data"></li>
</ul>
<script type='text/javascript' src='knockout-3.4.2.js'></script>
<script>
var ViewModel = function() {
var self = this;
self.titles= [
'Journy to the earth',
'effective study plans'
];
};
ko.applyBindings(ViewModel);
</script>
</body>
</html>
Upvotes: 0
Views: 593
Reputation: 15711
The problem is that you omitted the foreach part when changing the variable name:
<ul >
<!-- ko foreach: books -->
<li data-bind="text: $data"></li>
<!-- /ko -->
</ul>
You changed to
<ul >
<li data-bind="text: $data"></li>
</ul>
But should have changed to
<ul >
<!-- ko foreach: titles -->
<li data-bind="text: $data"></li>
<!-- /ko -->
</ul>
Notice that I changed the foreach instruction to use the new variable name.
Upvotes: 1