在knockout.js中设置组合的optionsText [英] Setting a combined optionsText in knockout.js

查看:73
本文介绍了在knockout.js中设置组合的optionsText的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的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: {}">

这样可以正常工作,显示人的FirstName并将值设置为LastName。

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: {}">

未捕获TypeError:对象#的属性'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); }

或者更好的是,在你的viewmodel中创建一个计算器:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆