Recently discovered an interesting behavior in KnockoutJS where subscription functions are evaluated before dependent computables. I'm looking for someone who can confirm this, as I haven't been able to find any information about the timing of Knockouts in the documentation or discussion forums.
This situation arises when working with a model structure like the one below...
var itemModel = function (i) {
var self = this;
self.Id = ko.observable(i.Id);
self.Title = ko.observable(i.Title);
self.State = ko.observable(i.State);
};
var appModel = function () {
var self = this;
self.Items = ko.observableArray() // <-- some code initializes an Array of itemModels here
self.indexOfSelectedItem = ko.observable();
self.selectedItem = ko.computed(function () {
if (self.indexOfSelectedItem() === undefined) {
return null;
}
return self.Items()[self.indexOfSelectedItem()];
});
};
In this scenario, when subscribing to the index field like so...
appModel.indexOfSelectedItem.subscribe(function () {
// Do something with appModel.selectedItem()
alert(ko.toJSON(appModel.selectedItem()));
}
The subscription function is being executed before the computed observable is recalculated with the new index value. This leads to getting the selectedItem() corresponding to the last selected index instead of the current selected index.
I have two questions:
- Is my understanding correct?
- If so, why should I utilize ko.computed() when a simple function can give me the current selected item every time it is called? Especially considering that ko.computed gets evaluated after everything has already completed and may no longer be needed.