Carl Onager
Carl Onager

Reputation: 4122

How to write to observable by name?

I'm writing a form filling page using Knockout and based on some old html forms, everything is good but the html forms have a button to copy a set of address data from one set of inputs to another, I'm trying to duplicate similar functionality in my ViewModel using this function:

self.CopyData = function (source, target) {
    for (var i = 0; i < source.length; i++) {
        self[target[i]] = self[source[i]];
    };
};

Where source and target are arrays of strings.

However I think that this is going to fail as I'm not writing to the knockout observable instead I'm overwriting it with a value. However I haven't found out how to do this the right way. From the documentation:

To write a new value to the observable, call the observable and pass the new value as a parameter. For example, calling myViewModel.personName('Mary') will change the name value to 'Mary'.

How do I write to a Knockout observable by name?

Upvotes: 1

Views: 58

Answers (1)

Roy J
Roy J

Reputation: 43899

An observable is simply a setter-getter function. You assign a value to an observable by invoking it with the value as an argument. To read the value of an observable, you invoke it with no argument.

To keep things clear, I'll use a couple of variables.

self.CopyData = function (source, target) {
    var sourceObs, destObs;
    for (var i = 0; i < source.length; i++) {
        sourceObs = self[source[i]];
        destObs = self[target[i]];
        destObs(sourceObs());
    };
};

Upvotes: 2

Related Questions