Assigning values to knockout observable dynamically determined by string name

knockout.jsobservablevariable-assignment

I've got two questions please:

I'm using knockout (I'm a KO noob sry) and I would like to assign a value to a specific knockout observable upon a click event but which should be only determined upon the click event itself (and the value I will pass to the data-bind=click)…can it be done please…can I get the knockout observable variable just upon its name (a string value) instead of having to know which observable I'm going to be assigning a value beforehand?

And, secondly less immportant, if such a function ko.ObservableByName(stringName) exists is it possible to use it somehow and assign the pre-selection of multiple select items upon page load..and how please?

I've tried to do this…I've used data-bind="click: loadData.bind($data, 'param1', 'param2')" and then I'm able to get those param1 and param2 string values by constructing an event handler in my knockout viewmodel that goes something along the line of:

self.loadData = function (src, dest) {
    //dest is 'param1', src is 'param2', both are stings
    if (src == 'param1')
       self.p1observable($('#' + dest).val());
    else
       self.p2observable($('#' + dest).val());
}

My biggest problem with this is that I have to construct the function with p1/p2 observables already specified and hard-coded in it, but really I'd like to get param1 and param2 to be used as names or references by name of some of my observables, which I could then pass at will (alongside either a value to be assigned, or better yet another observable I'd like to copy the value from to the first one), and thus I could assign passed in values in the click function call directly to an observable of my choosing (and not have a large number of such small functions)…

Maybe I'm going at it the wrong way? Maybe I shouldn't be passing in string values at all… Maybe I should of tried to pass in an observable object, but how can one do that inside data-bind, do you just write myViewModel.myObservable or something like that?

Best Answer

If you have your parent object, then you can access an observable by using this syntax:

viewModel[observableName]

and set the value like:

viewModel[observableName](newValue)

Here is a sample where you can choose the property name from a dropdown and then set the value accordingly and another one where the button is bound directly to setting an observable/value: http://jsfiddle.net/rniemeyer/CTnUQ/

Related Topic