Assigning values to knockout observable dynamically determined by string name

http://stackoverflow.com/questions/8905052/assigning-values-to-knockout-observable-dynamically-determined-by-string-name

by Doug Hill

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.0.0.js"></script>
<select data-bind="options: propertyNames, value: selectedProperty"></select>

<input data-bind="value: currentValue" />

<button data-bind="click: setValue">Set Value</button>

<hr/>

<button data-bind="click: setValue2.bind($data, 'two', 'Jon')">Set two to Jon</button>

<hr/>

<div data-bind="text: ko.toJSON($root.properties)"></div>

JavaScript

var viewModel = {
    propertyNames: ["one", "two", "three"],
    selectedProperty: ko.observable(),
    currentValue: ko.observable(),
    properties: {
       one: ko.observable("Bob"),
       two: ko.observable("Ted"),
       three: ko.observable("Ann")
    },
    setValue: function() {
       this.properties[this.selectedProperty()](this.currentValue());   
    },
    setValue2: function(propName, value) {
        this.properties[propName](value);
    }
};

ko.applyBindings(viewModel);