knockout observable array + selectbox

时间:2013-02-22 02:47:41

标签: knockout.js drop-down-menu ko.observablearray

我正在尝试在带有可观察数组的选择框上设置选项。我可以选择填充,但数组显示为一个选项,现在看起来没有任何价值。

以下是fiddle和以下代码:

var Model = function (properties) {
    this.AvailableLenders = ko.observableArray();

    this.ModifyLenders = function (newProperties) {
        var lenders = [],
            count = 0;

        ko.utils.arrayForEach(newProperties || properties, function (item) {
            var lender = item.Lender;

            if (lender) {
                if (lenders.indexOf(lender) == -1) {
                    lenders[count] = lender;

                    count++;
                }
            }
        });

        this.AvailableLenders.removeAll();

        return this.AvailableLenders.push(lenders.sort());
    };

    this.ModifyLenders();
};

ko.applyBindings(new Model([{Lender: "ASB"}, {Lender: "ANZ"}]));

HTML:

<select multiple="multiple" name="Lender" id="Lender" data-bind="options: AvailableLenders, optionsCaption: 'Please select a lender'"></select>

1 个答案:

答案 0 :(得分:1)

我发现了问题。

问题是你是在一个可用的ListLenders数组索引中推动Lender数组

var Model = function (properties) {
this.AvailableLenders = ko.observableArray();

this.ModifyLenders = function (newProperties) {
    var lenders = [],
        count = 0;

    ko.utils.arrayForEach(newProperties || properties, function (item) {
        var lender = item.Lender;

        if (lender) {
            if (lenders.indexOf(lender) == -1) {
                lenders[count] = lender;

                count++;
            }
        }
    });

    this.AvailableLenders.removeAll();

    console.log("lenders ", lenders)
    console.log("lenders.sort() ", lenders.sort())

我在下面做了更改。现在你可以理解它为什么会发生了

在你的小提琴中添加这两行并检查发生了什么

    this.AvailableLenders.push(lenders[0]);
    this.AvailableLenders.push(lenders[1]);
    return this.AvailableLenders.push(lenders.sort());
   };

  this.ModifyLenders();
  };

 ko.applyBindings(new Model([{
  Lender: "ASB"
 }, {
  Lender: "ANZ"
 }]));

将其标记为答案