【问题标题】:KnockoutJS having trouble using custom optionsText: on ko.mapping.fromJS dataKnockoutJS 在使用自定义 optionsText 时遇到问题:关于 ko.mapping.fromJS 数据
【发布时间】:2013-07-13 02:19:54
【问题描述】:

我正在使用 ASP.NET MVC、Web API 和 KnockOutJS 创建一个站点。使用 Web API,我返回一个 Location 对象列表,该列表通过 JQuery AJAX 调用获取,并存储在 observableArray 中。

        $.getJSON(baseLocationUri, function (data) {
            $.each(data, function (key, val) {
                self.locations.push(ko.mapping.fromJS(val));
            });
        });

返回的数据示例可能如下所示(为简洁起见进行了修剪): [{"LocationId":1,"DisplayName":"Starbucks","Address":"123 Main St."}]

这很好用,我在其他地方也使用过同样的代码。

我还有一个绑定到 observableArray 的多选列表。如果我以这种方式编写选择,使用“DisplayName”作为选项文本:,它可以正常工作:

<select multiple="multiple" data-bind="options: locations, selectedOptions: selectedLocations, optionsText: 'DisplayName'"></select>

同样,如果我将 DisplayName 作为函数返回,它仍然有效:

<select multiple="multiple" data-bind="options: locations, selectedOptions: selectedLocations, optionsText: function (item) { return item.DisplayName }"></select>

但是——如果我尝试添加另一个参数——它会失败。我在 UI 中看到的只是“未定义”。

<select multiple="multiple" data-bind="options: locations, selectedOptions: selectedLocations, optionsText: function (item) { return item.DisplayName + ' | ' + item.Address }"></select>

还有一件事。如果我删除 AJAX 调用和映射,并在 JavaScript 中创建一个 Location 对象的 observableArray,那么最后的代码就可以正常工作。

我错过了什么?

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    你试过了吗:

     function (item) { return item.DisplayName() + ' | ' + item.Address() }
    

    因为 ko.mapping.fromJS(val) 将 DisplayName 和 Address 转换为 observables。

    【讨论】:

    • 再一次,一双新的眼睛看到了问题。谢谢!!
    猜你喜欢
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多