Josh M.
Josh M.

Reputation: 27781

Bind select options to global variable/array?

Suppose I have the following Javascript:

var Option = (function ()
{
        function Option(value, text)
        {
            this.value = value;
            this.text = text;
        }

        return Option;
})();

var QuestionTypes = (function ()
{
    QuestionTypes.chooseOne = new Option("ChooseOne", "Choose One");
    QuestionTypes.chooseMany = new Option("ChooseMany", "Choose Many");
    QuestionTypes.text = new Option("Text", "Text");
    QuestionTypes.all = function ()
    {
        return
        [
            QuestionTypes.chooseOne, 
            QuestionTypes.chooseMany, 
            QuestionTypes.text
        ];
    };

    return QuestionTypes;
})();

And this HTML:

<select data-bind="value: type, options: QuestionTypes.all, optionsValue: value, optionsText: text" />

So the select is bound to my "static" variable QuestionTypes. I expect the resulting select to look something like this:

<select data-bind="value: type, options: QuestionTypes.all, optionsValue: value, optionsText: text">
    <option value="ChooseOne">Choose One</option>
    <option value="ChooseMany">Choose Many</option>
    <option value="Text">Text</option>
</select>

Basically, how do I bind to something that is global and NOT on the model itself?

Upvotes: 0

Views: 1986

Answers (1)

Michael Best
Michael Best

Reputation: 16688

You can bind to global variables just fine. They are available in bindings just like anywhere else.

The problem in your example is that optionsValue and optionsText need to be strings.

options: QuestionTypes.all, optionsValue: 'value', optionsText: 'text'

Upvotes: 5

Related Questions