Knockout.js send back to the server to update the model

I know that you can create bindings in two ways in knockout.js. This changes the model in javascript as soon as you change the view and vice versa. I need a way to notify and send these changes back to the server. Therefore, I really need to make a message on the server. How can i do this?

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

+6
source share
3 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() } }); }); } 

For each viewmodel property you do not need individual โ€œmanual subscriptionsโ€. Just define a ko.computed . All ko.computed automatically notified of changes in the observables on which they depend. In the above code, the calculated values โ€‹โ€‹depend on the $.ajax observed (in the data argument of jQuery $.ajax ). Whenever the value of the observable changes, the completed ko.computed function will execute and pass the new value (s) to the server.

+14
source

How about a manual subscription ?

  • Manual subscriptions can be thought of as bindings for your presentation model. Bindings allow your user interface to respond to changes in your view model, while manual subscriptions allow your view model to respond to changes in yourself. This may mean creating updates for other related objects in your view model.

  • A common example is to start updating observable via AJAX when other observable changes change, for example, when the checkbox is checked or the value of the drop-down list is changed. In this case, the manual subscription acts as an asynchronous calculated observable.

+1
source

I do this via json (only one way):

load your binding to from json String (example):

 userSettingsModel = ko.mapping.fromJSON('${userSettingsJSON}'); ko.applyBindings(userSettingsModel); 

Send the modified ko object back to the server (example):

 function saveConferencesFilter() { // console.log(ko.mapping.toJSON(userSettingsModel)); $.ajax({ type: 'PUT', url: '/AudioPlace/userSettings/rest', dataType: 'json', contentType: 'application/json;charset=UTF-8', data: ko.mapping.toJSON(userSettingsModel), success: function (data) { getConferences(); } }); } 
0
source

All Articles