在knockout.js 中设置组合optionsText [英] Setting a combined optionsText in knockout.js
问题描述
我想在我的 optionsText 字段中组合两个返回值,我认为这很简单,但我显然错了.我还使用了普通视图模型之外的选项字段的值.这是原文:
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.
下一段抛出错误:
<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: {}">
未捕获的类型错误:对象 # 的属性 'FirstName' 不是函数
Uncaught TypeError: Property 'FirstName' of object # is not a function
推荐答案
你确定 FirstName 和 LastName 是可观察对象?如果你不确定,试试这个:
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);
};
还有:
optionsText: 'FullName'
这篇关于在knockout.js 中设置组合optionsText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!