1

我试图弄清楚淘汰赛中的订阅功能是如何工作的,我希望有人能帮助我。我基本上是在尝试从数组中获取选定的值并将其绑定到跨度元素使用subscribe()

我希望通过使用选择器或其他事件来做到这一点而不涉及用户界面的意识。根据我从文档中阅读的内容,订阅应该在选择项目时更新值。我在这里遗漏了一些东西,因为我无法将任何东西绑定到 span 标签。

对于我所缺少的内容,我将不胜感激。

谢谢

小提琴链接下方的代码和小提琴

js

var myProduceModel = function(){
 var self = this;


    self.produceList = ko.observableArray([
        {productName: "Apples", productCode: "#FF0000"},
        {productName: "Oranges", productCode: "#FF9200"},
        {productName: "Grapes", productCode: "#652C90"},
        {productName: "Figs", productCode: "#67070D"}    
        ]);

    self.selectedItem = ko.observable();
    self.selectedField = ko.observable();

    self.selectedItem.subscribe(function(item){
        self.selectedField(item.productName);
        return item.productCode;
    });
};

    ko.applyBindings(new myProduceModel());

htm

<select data-bind="options: produceList, optionsText:'productName', optionsvalue: 'selectedItem', optionsCaption: 'Choose...'"></select>

<hr/>
<span data-bind="text: selectedItem().productCode"></span>
4

1 回答 1

2

您正在滥用selectedValue用于告诉对象的哪个属性用作选定值的选项。

要设置所选值本身,您需要使用value绑定。

因此,将您的绑定更改为:

<select data-bind="options: produceList, 
                   optionsText:'productName', 
                   optionsCaption: 'Choose...',
                   value: selectedItem"></select>

演示JSFIddle

data-bind="text: selectedItem().productCode"如果没有选择任何内容,您的小提琴中还有一个问题将失败。所以你需要类似的东西 data-bind="text: selectedItem() && selectedItem().productCode"或使用with绑定。

于 2013-10-09T15:34:12.803 回答