Please refer to this question as it helped solving 50% of my issue:
the other 50% of issue is updating view, if you call ko.applyBindings(viewModel);
twice, you get an error Uncaught Error: You cannot apply bindings multiple times to the same element.
No one online ever proposed a solution to this, even on the official knockout site they mentioned:
// Every time data is received from the server:
ko.mapping.fromJS(data, viewModel);
which is not working either. Anyone knows what the proper method is to update my view each time I fetch new data, knowing that the view is already initialized via ko.applyBindings(viewModel);
?
Edit:
HTML :
<select class="input-short artist-list" data-bind="foreach: model">
<option value="1" selected="selected" data-bind="text: name"></option>
</select>
JS
var viewModel = {
model: ko.observableArray()
};
$(window).load(function(){
fetchArtists();
})
function fetchArtists() //this function fetches all artists
{
// load data
$.post( "../db/fetch/", { table: "artists"})
.done(function( data ) {
// artists=JSON.parse(data);
data=JSON.parse(data);//data is array of objects e.g [{name:"xxx"},{name:"yyy"}]
artists.model = ko.mapping.fromJS(data);
ko.applyBindings(artists);
});
}