I am trying to bind a select element on a page using knockoutjs. The select element needs to display option built from an observable array of objects. I have created a computed property to create an array of nicely formatted values using my observable array:-
//my observable array of objects
self.TestTypes = ko.observableArray([ { Test: 'A'}, {Test: 'B'}]);
//my computed function to create {value, text} objects formatted nicely
self.Options = ko.computed(function() {
var options = [];
for(var i = 0; i < self.TestTypes().length; i++) {
options.push({ value: self.TestTypes()[i].Test, text: 'Test ' + self.TestTypes() [i].Test });
}
return options;
}, self);
I can use this to effectively populate my select element options without an issue.
I also have an object (same type as the objects in my observable array), that should drive the value of the select element:-
self.Test = ko.observable(new TestModel(model.Test));
The definition of my example object is here (it's very simplified)
var TestModel = function(model) {
var self = this;
self.Test = ko.observable(model.Test);
};
Finally, I try to bind everything to my select element, but the value doesn't take notice of my self.Test object:-
<select data-bind="value: Test.Test, options: Options, optionsText: 'text', optionsValue: 'value'"></select>
I have a feeling that this has something to do with references, but I can't get my head around it. I have a full example of my (extremely simplified) code on jsFiddle. Does anyone know what I'm doing wrong?
return this. Is it the case on your real code? - GôTônewkeyword, JS will return this inherently. As an aside, you might consider adding the following to ensure that the function is always executed as a constructor:if(!(this instanceof TestModel)) return new TestModel(model);- Vinney Kelly