使用fromJS更新后,选项文本成为函数字符串 [英] Option text becomes a function string after updated with fromJS

查看:48
本文介绍了使用fromJS更新后,选项文本成为函数字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么从ko.mapping.fromJS更新值后,选项文本为什么会转换为函数的字符串?

Why does the option text get converted to a string of a function after the values has been updated from ko.mapping.fromJS?

样本: http://jsfiddle.net/tYnc6/24/

HTML:

<div>
    <select data-bind="options: items, value: selected, optionsText: function(item) { return ('[' + item.Id + '] ' + item.Name) }, optionsCaption: 'Choose...'"></select>
    <button data-bind="click: update">Update</button>
</div>

Javascript:

​ Javascript:

var mapping = {
        key: function(data) {
            return ko.utils.unwrapObservable(data.Id);
    }
};

viewModel = {
    items: ko.observableArray([
        {Name: 'foo', Id: '1'},
        {Name: 'bar', Id: '2'}
    ]),
    selected: ko.observable(),

    update: function() {
        data = [
            {Name: 'foo', Id: '1'},
            {Name: 'bar', Id: '2'},
            {Name: 'baz', Id: '3'}
        ];
        ko.mapping.fromJS(data, mapping, this.items);
    }
}
ko.applyBindings(viewModel);

请注意,按下更新后,选项文本将变为功能.

Notice that after update has been pressed the option text becomes a function.

推荐答案

通过映射插件传递的数据现在已将NameId变为可观察的对象.因此,当您的函数执行'[' + item.Id + '] ' + item.Name时,您正在将字符串与可观察对象(它们是函数)连接起来.

The data that has been passed through the mapping plugin has now turned Name and Id into observables. So, when your function does '[' + item.Id + '] ' + item.Name, you are concatenating strings with observables (which are functions).

如果NameId始终是可观察的,则您需要这样做:

If the Name and Id are always observables, then you would want to do:

'[' + item.Id() + '] ' + item.Name()

如果您要支持可观察的或不可观察的,则可以执行以下操作:

If you want to support either observables or non-observables, then you could do something like:

'[' + ko.utils.unwrapObservable(item.Id) + '] ' + ko.utils.unwrapObservable(item.Name)

ko.utils.unwrapObservable将正确返回可观察值或不可观察值.

ko.utils.unwrapObservable will properly return the value for an observable or non-observable.

这篇关于使用fromJS更新后,选项文本成为函数字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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