In my model I have a property that is loaded asynchronously. I want it to generate another model property after it loads.
I was thinking about subscription that could fire after the 1st property changes, generates the 2nd property and then get disposed - I don't know how can I dispose subscription from inside itself.
Is there a way to fire one time event after observable property changes?
To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.
It can be like this. var model = { "xId": ko. observable(0), "xName": ko. observable(null), "Type": ko.
To apply bindings for the whole HTML document, it can be done using the Knockout function applyBindings() with passing the view model as the first and the only parameter: ko. applyBindings(viewModel); To apply Knockout for a part of the HTML document, pass the DOM element as a second parameter: ko.
When you subscribe to KnockoutObservable<string[]> , then you will receive a string array ( string[] ) The other one is an array of observables ( KnockoutObservable<string> ), each one resolving to a result with a type string. When you wish to receive the string array, you should use KnockoutObservable<string[]>
To dispose subscription from inside itself just create reference to it:
var subscription = yourObservable.subscribe(function (newValue) {
...
subsription.dispose();
});
If you don't want to write this code every time, you can extend observable with new method:
ko.subscribable.fn.subscribeOnce = function (handler, owner, eventName) {
var subscription = this.subscribe(function (newValue) {
subscription.dispose();
handler(newValue);
}, owner, eventName);
return subscription;
};
...
// usage
var subscription = yourObservable.subsribeOnce(yourHandler);
And dont' forget to dispose subscription on component disposal in case it was not fired.
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