Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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'

Solution 2:

how optionsText works is it looks for the property 'FirstName' on the options array that is is bound to. So if your extra person array has a 'FirstName' and a 'LastName' you can extend a computed property to hold full name.

functionViewModel(){
    varself = this; 
    self.peopleList = ko.observableArray(); 
}
functionPerson(f, l){
    varself = this; 
    self.FirstName = ko.obserable(f); 
    self.LastName = ko.obserable(l); 
    self.FullName = ko.computed(function(){
        returnself.FirstName() + ' ' + self.LastName();
    });
}

If they are not observables you don't want to be calling them [ what () does ] it would in that case I would just have a function living on the view model that puts them together which you call from the binding.

Post a Comment for "Setting A Combined Optionstext In Knockout.js"