I have a problem with my knockout implementation. I am new to knockout so would appreciate the help.
I have the following code:
function updateViewModel() {
if (typeof groupId == 'undefined') {
groupId = getDefaultGroupId();
}
$.getJSON("api/livestatusgroup/children/" + groupId)
.done(function (data) {
ko.mapping.fromJS(data, liveStatusViewModel.groups);
groupsLoaded();
});
$.getJSON("api/livestatusgroup/resources/" + groupId)
.done(function(data) {
ko.mapping.fromJS(data, liveStatusViewModel.resources);
resourcesLoaded();
});
this.resourceImagePath = ko.computed(function () {
return "../Image/" + this.ResID;
}, this);
}
function ViewModel() {
var self = this;
self.resources = ko.mapping.fromJS([]);
self.groups = ko.mapping.fromJS([]);
}
var vm = new ViewModel();
ko.applyBindings(vm);
Unfortunately, the computed observable function resourceImagePath is not correctly capturing the ResID for my resource, so I end up with urls like /Image/undefined.
What am I missing? I have checked and the ResID field definitely exists in the view model.
S
When you implement a ko.computed
observable, it only creates a dependency for observables that are referenced within the computed function. Remember that observables must be referenced by executing them, because they are functions - it's this action that allows the computed function to detect and track a dependency.
Otherwise, the computed function will only be able to use the value that is available at the time the computed function is first executed.
This code references this.ResID
, but doesn't have any dependency on it due to not treating ResID as an observable.
this.resourceImagePath = ko.computed(function () {
return "../Image/" + this.ResID;
}, this);
Try ensuring that this.ResID
is, in fact, an observable, and add parentheses like this:
this.resourceImagePath = ko.computed(function () {
return "../Image/" + this.ResID();
}, this);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.