0
votes

I am using knockout in my project. I have multiple viewmodel, each viewmodel have its own save function implemented in it. Now whenever user clicks on save button the viewmodel data post to the server, i want to block the save button until the response came back from server.

Currently i am handling this by creating an extra observable property saving in each viewmodel. So when user click over the save button i am setting saving observable to true and in callback i am setting it to false. And i have bind this saving property with the button using knockout disable binding.

But i feel that this approach is not good and it contains the following big drawbacks:

  1. For this i have to add an extra property in each viewmodel.
  2. I have to add multiple line of code like setting it to true and again set it to false.
  3. The approach is not centralize, the code for this approach is scattered.

So i want to know is there any other better way to handle this, a plugin or some standard way ??

Edit

Just to clarify, my question has nothing to do with asp.net postback, the question is how i can handle efficiently the ajax, like block the save button, displaying the response message etc ??

3
Just to clarify, you're doing an ajax POST and not an ASP.NET postback, right?xdumaine
yes, i am doing ajax postuser1740381

3 Answers

0
votes

This is generally what makes a viewmodel a viewmodel. In a pattern like MVC, your controller shouldn't really have any idea what your view looks like, what controls it has, or what it's state is, and your model only contains data for the view to model. In an MVVM pattern, as knockout is, your viewModel actually does have knowledge of the current states of controls on the view. This isn't to say your viewmodel should directly update the view, but it usually will contain properties that are bound to states of the view. Things like SaveButtonEnabled or IsSavingData or even things like StatusLabelColor are accepted in a viewmodel.

0
votes

Perhaps use $.ajaxSetup(). You call this in your document ready function.

$.ajaxSetup({
    beforeSend: function(jqXHR) 
    {
        //this will be called before every 
        //ajax call in your program
        //so perhaps, increment an observable viewmodel variable
        //representing the number of outstanding requests
        //if this variable is > 0 then disable
        //your button
    },
    complete: function(jqXHR) 
    {
        //this will be called after every 
        //call returns
        //decrement your variable here
        //if variable is zero, then enable button
    }
}); 
0
votes

I'd recommend you take a look at http://durandaljs.com/, a framework using Knockout and has some great data patterns, even if you don't use it directly.