I'm attempt to establish a grid and update it with more records via JSON. In this simple example I am able to achieve the required functionality but I can only update / push one JSON record. I would like to be able to add multiple records via JSON? How could I achieve this? I assumed I might have to create some sort of for loop and push each JSON result to the observable but I was hoping that knockout might have a better way of updating / parsing via JSON?
Heres a copy of what I have achieved so far: http://jsfiddle.net/sparkhill/crSbt/
function Users(user_id, password) {
this.user_id = ko.observable();
this.password = ko.observable();
}
var viewModel = {
users: ko.observableArray([]),
addUser: function () {
this.users.push({
user_id: "",
password: ""
});
},
addJSON: function () {
//Works Fine
var JSONdataFromServer
='{"user_id":"frances","password":"password"}';
//More than one result - wont map - Would Ideally like to map lots of records at one time
//var JSONdataFromServer ='{"user_id":"frances","password":"password"}, {"user_id":"frances","password":"password"}';
var dataFromServer = ko.utils.parseJson(JSONdataFromServer);
this.users.push(dataFromServer);
//Tried
//this.users.push(JSON.parse(JSONdataFromServer));
}
};
viewModel.users();
ko.applyBindings(viewModel);
</script>
Update this seems to work but I wonder if their is a more efficient method?
addJSON: function () {
//Works Fine
var JSONdataFromServer
='[{"user_id":"frances","password":"password"},{"user_id":"timmy","password":"password"}]';
var results = JSON.parse(JSONdataFromServer);
var i = results.length;
for(var i = 0; i < results.length; i++){
this.users.push(results[i]);
};