Reputation: 412
AM working on a simple knockout application. Am able to do a successfull binding of data to the view layer. Howsoever on changing the data array for a button click event the values are not getting reflected on to the view layer.
Following is my code:
<!Doctype HTML>
<html>
<head>
<script src="knockout-3.1.0.js"></script>
<script>
/*Sample data array that will have the changing values*/
var sampledata = [{ title1:"abc",title2:"abc2" },
{title1:"def",title2:"ghi"}];
/*View model that is used for binding*/
function sampleViewModel() {
var self=this;
self.sampledata2 = ko.observableArray(sampledata);
}
var my = { viewModel: new sampleViewModel() };
/*Applying bindings using knockout*/
function initialize() {
ko.applyBindings(my.viewModel);
}
/*Changing values for the onclick of the button*/
function changevalues(){
my.viewModel.sampledata2([{ title1:"zzz1",title2:"yyy1" }, {title1:"zzz2",title2:"yyy2"}]);
}
</script>
</head>
<body>
<div id="frame" data-bind="foreach: sampledata">
<!-- Displays the "title" field. -->
<h4 id="duration" data-bind="text: title1"></h4>
<h4 id="time" data-bind="text: title2"></h4>
</div>
<button id="clickme">Click me to change the data values</button>
<script>
document.getElementById('clickme').addEventListener('click',changevalues,false);
initialize();
</script>
</body>
</html>
I would like to know how I can change the value of that data array for the button click event. I know this has something to do with ko.observableArray(). But I have a doubt that am complicating the actual logic. Would be great if someone can provide a solution on the same.
Upvotes: 0
Views: 585
Reputation: 1860
You need to make self.sampledata2 an observable array.
self.sampledata2 = ko.observableArray(sampledata);
You need to store the view model in a variable (let's say viewModel), and then update it as follows:
viewModel.sampledata2([{ title1:"zzz1",title2:"yyy1" }, {title1:"zzz2",title2:"yyy2"}]);
Do not change sampledata directly.
Upvotes: 2