Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js post back to server to update model

I know for a fact that you can create 2 way bindings in knockout.js. This changes the model in javascript once you change the view and the opposite. I need a way to notify and send this changes back to the server. So I pretty much need to do a post to the server. How can I do this?

What I mean by this, is that I somehow need to attach an event handler so whenever I change once of my models it automatically posts back to the server the changes.

like image 324
Alecu Avatar asked Oct 31 '12 15:10

Alecu


2 Answers

function MyViewModel() {
    var self = this;
    self.value1 = ko.observable();
    self.value2 = ko.observable();
    ko.computed(function() {
        $.ajax({
            url: '/path/to/server/endpoint',
            type: 'POST',
            data: {
                value1: self.value1(),
                value2: self.value2()
            }
        });
    });
}

You should not need individual "manual subscriptions" for each viewmodel property. Just define a ko.computed. All ko.computeds are automatically notified of changes to the observables that they depend on. In the code above, the computed depends on the value1 and value2 observables (in the data argument to the jQuery $.ajax function). Whenever the value of an observable changes, the wrapped ko.computed function will execute, and submit the new value(s) to the server.

like image 64
danludwig Avatar answered Nov 15 '22 14:11

danludwig


How about a manual subscription?

  • Manual subscriptions can be thought of like bindings for your view model. Bindings allow your UI to react to changes in your view model, while manual subscriptions allow your view model to react to changes to itself. This may mean making updates to other related objects in your view model.

  • A common example is triggering an update to an observable via AJAX when another observable changes, such as when a checkbox is checked or a dropdown value is changed. In this case, the manual subscription acts like an asynchronous computed observable.

like image 39
Jim G. Avatar answered Nov 15 '22 14:11

Jim G.