Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to save changes in MVVM/Knockoutjs Web App?

I've been playing with KnockoutJS and absolutely love how much it simplifies the design from every angle by keeping stuff from falling through the cracks. My question is what is the recommended "best practice" for saving the data back to the server? My understanding is that in a connected MVVM, the first "M" is the data layer and so the dependency tracking and notifications in the ViewModel trigger saves directly back to the data layer. In a JavaScript app, we are disconnected and selectively save back to the server using AJAX.

The app I'm currently using it in is MVC3 and I absolutely get how to write a "Save" action on my controller, plop a "Save" button somewhere on my page, post the whole ViewModel to that Save action and then persist that to the database. But what about when you make a quick edit and then save it again? Or what if a save button doesn't fit the flow of the design? Instead, you want to post to the action every time a change is made on the form with no save button at all? The ideas that I've bounced around are:

  • Post the whole ViewModel every time any change is made and make the Action figure out what is new and what isn't (not ideal, especially for large models, if nothing else because the data transmitted on each save would be unnecessarily large).
  • Add a property to each item in the ViewModel that tracks whether it is new and/or changed since the last save. Then, grep out those items and post only those to the server (I haven't tested this, but I assume this can be done using the _destroy property, as intended for a Rails app).
  • Separate into as many smaller ViewModels as is plausible so that any pain from the first two options is minimized (this should probably be done regardless).
  • Some other better way?

I'm hopeful there are some good ideas out there that I haven't thought of. To be able to declaratively bind everything AND still save efficiently would be awesome.

like image 674
Jorin Avatar asked Apr 14 '11 23:04

Jorin


1 Answers

I just got back from Mix11 where I attended this session about Knockout.js. It might be worth your while to watch Steve Sanderson crank out a full CRUD demo.

like image 166
Paulczy Avatar answered Oct 13 '22 01:10

Paulczy