Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a combined optionsText in knockout.js

I want to combine two return values in my optionsText field, I thought this would be simple, but I am apparently wrong. I'm also using a value for the options field that is outside the normal view model. Here is the original:

<select style="width: 180px" data-bind="visible: false, value: fields.person, options: $root.extra.personList, optionsText: 'FirstName', optionsValue: 'LastName' }, select2: {}">

This works fine, displays the person's FirstName and sets the value as LastName.

This next piece throws an error:

<select style="width: 180px" data-bind="visible: false, value: fields.person, options: $root.extra.personList, optionsText: function (item) { return item.FirstName() + '-' + item.LastName() }, optionsValue: 'LastName', select2: {}">

Uncaught TypeError: Property 'FirstName' of object # is not a function

like image 580
Organiccat Avatar asked Jan 27 '14 18:01

Organiccat


Video Answer


1 Answers

You sure FirstName and LastName are observables? If you're not sure, try this:

optionsText: function(item) { return ko.unwrap(item.FirstName) + '-' + ko.unwrap(item.LastName); }

Or better yet, create a computed in your viewmodel:

self.FullName = function() {
    return ko.unwrap(self.FirstName) + '-' + ko.unwrap(self.LastName);
};

And:

optionsText: 'FullName'
like image 114
sroes Avatar answered Oct 31 '22 18:10

sroes