How to Update or Refresh the ViewModel Data and then the View

5,876 views
Skip to first unread message

gsr...@gmail.com

unread,
Aug 29, 2012, 6:03:31 PM8/29/12
to knock...@googlegroups.com
I'm new to knockout and trying to figure out how to make it work for my current project.  Specifically, I have a viewmodel that is loaded with json data via an ajax call to the server.  Once the data is received, the knockout bindings are applied and the data is displayed  in the html on the screen.  Works good.

Now the difficult part... (at least for me)  Also, in the html, I have elements (checkboxes, radio buttons, dropdowns, etc.) in which the user can select values.  Once done selecting values, this user clicks a button to update the data on the page.  Thus, the button click sends the selected values back to the server to requery the database for a new collection of data.  The server then needs to send the updated list of json back to the page and knockout, and the viewmodel and the html display needs to be updated with the new data.  Or, at least this is how I need it to work.  I've been banging my head on how to do this for a while now.

So, after querying the database, binding knockout and the viewmodel, and displaying data, how can I request different data by requerying the database, get new data from the server, rebind knockout and the viewmodel to the new data, and display the new data in the same html page (just with the updated data)?????

Thanks in advance!

gsr...@gmail.com

unread,
Aug 31, 2012, 11:10:43 AM8/31/12
to knock...@googlegroups.com, gsr...@gmail.com
Ok...let me ask this in a slightly different way...  What if I had a button on my page, which upon clicking it produced another ajax call to the server to get a new/updated set of data.  How can I replace the current set of data in the viewmodel and view with the new/updated set of data returned from a second ajax call to the server?

Casey Corcoran

unread,
Aug 31, 2012, 11:35:19 AM8/31/12
to knock...@googlegroups.com
At the most basic level, you just update your viewModel's observables with the new data from the server:

viewModel.someValue = ko.observable();

function onDataFromServer( data ) {
viewModel.someValue( data.someValue );
}

Then your view updates accordingly. There are also automated ways of doing so with the "mapping" plugin. I haven't used it personally so I can't speak to implementation.

For saving your viewModel ko has utility methods like toJSON which will unwrap your observables and give you a plain structure to send to the server.

Have you been through the tutorial site at http://learn.knockoutjs.com yet? I would highly recommend it, it has some ajax examples just like you're looking for.

Casey Corcoran
Reply all
Reply to author
Forward
0 new messages