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() {
$.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.computed
s 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With