Alecu Alecu - 3 months ago 10x
Javascript Question

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.

function MyViewModel() {
    var self = this;
    self.value1 = ko.observable();
    self.value2 = ko.observable();
    ko.computed(function() {
            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.