1
votes

Question is regarding optionsText binding to get fullName.

JsFiddle

When I do this it works as in Knockout doc,

<select multiple="multiple" width="50" data-bind="options: leftItems,optionsText: function(item) {return item.firstName() + ' ' + item.lastName() }, selectedOptions:leftSelectedItems"></select>

But when I move the function to View Model and try to use it does not work,

Here is my select,

<select multiple="multiple" width="50" data-bind="options: leftItems,optionsText: returnFullName(item), selectedOptions:leftSelectedItems"></select>

In my View Model,

    self.returnFullName = function(item) {
        console.log("self.returnFullName called.");
        console.log(item);
        return item.firstName() + ' ' + item.lastName();
    };

Error I am getting is that "Uncaught ReferenceError: Unable to process binding "options: function (){return leftItems }" which is even not related to optionText.

Am I missing something?

1
the actual error you are getting is : Uncaught ReferenceError: Unable to process binding "options: function (){return names }" Message: item is not definedRohith Nair
Does this answer your question? Setting a combined optionsText in knockout.jsclaytond

1 Answers

2
votes

You don't need to pass it as you do. But you can follow any of these methods.

  • Method1

You can just call the viewmodel function and the first parameter will implicitly have the $data parameter.

<select multiple="multiple" width="150" data-bind="options: names,optionsText: returnFullName"></select>

and in VM

 self.returnFullName = function(item) {
     console.log(item);
        return item.firstName + " " + item.lastName;

    }; 

Jsfiddle:-

http://jsfiddle.net/mtfv6q6a/10/

  • Method 2

Bind the $data and pass it as you do.

<select multiple="multiple" width="150" data-bind="options: names,optionsText:returnFullName.bind($data);"></select>

Jsfiddle:-

http://jsfiddle.net/mtfv6q6a/42/

  • Method 3:-

You can wrap it in a function call and call like this:-

<select multiple="multiple" width="150" data-bind="options: names,optionsText:function(data){ return returnFullName(data);}"></select>

Jsfiddle:-

http://jsfiddle.net/mtfv6q6a/51/