Knockout条件样式的"未绑定"SELECT元素的选项元素

Tim*_*Tim 4 css conditional knockout.js

我页面上的各种输入都通过敲除绑定到视图模型,比方说客户记录.这一切都很好.

现在,我想在页面顶部放置一个SELECT,其中包含所有客户的列表.用户将选择一个客户,该记录将从数据库中获取,并且数据将绑定到视图模型.

我的问题涉及SELECT列表中项目的条件样式.它将绑定到一组客户对象.Customer对象定义有一个名为hasExpired的函数:

   var Customer = function (id, name, expiryDate) {
    this.id = id;
    this.customerName = name;
    this.expiryDate = expiryDate;
    this.hasExpired =  function() {
        return this.expiryDate == null ? false : true; 
      };
    };
Run Code Online (Sandbox Code Playgroud)

ViewModel,页面上的输入绑定到的ViewModel如下所示:

      function ViewModel() {
            var self=this;
             self.customerRegion = ko.observable(),
             self.customerName = ko.observable(),
             .
             .
             .
             self.allCustomers = Customers,  // Customers is an array of Customer objects
             self.selectedCustomer = ko.observable()



     }
Run Code Online (Sandbox Code Playgroud)

这个淘汰赛绑定工作; SELECT正确填充了客户列表:

    <select id="customerSelect" 
             data-bind="options: allCustomers,
            optionsText: 'customerName', 
            value:   selectedCustomer />
Run Code Online (Sandbox Code Playgroud)

我想为单个OPTIONS设置样式,如果合适,添加"过期"类.

Customers SELECT中的各个项目未绑定到视图模型.SELECT功能类似于导航菜单.选项绑定到allCustomers数组中的customer对象.

如何告诉knockout参考绑定到每个OPTION的客户对象的hasExpired属性,以确定该特定选项是否应该获取该expired属性?

我希望客户保留在"选择"列表中,但显示为具有删除格式.

SELECT是否需要自己的视图模型?

Ori*_*eil 8

绑定选项有一个参数(optionsAfterRender),其允许的选项元素的额外的处理.请参阅注释2:对生成的选项进行后处理(通过链接文档).

除非我误解了数据模型的结构,否则所需的只是回调

self.setOptionStyling = function(option, item) {
   ko.applyBindingsToNode(option, {css: {expired: item.hasExpired()} }, item);
}
Run Code Online (Sandbox Code Playgroud)

绑定到optionsAfterRender参数:

<select id="customerSelect" 
        data-bind="options: allCustomers,
                   optionsText: 'customerName', 
                   value: selectedCustomer,
                   optionsAfterRender: setOptionStyling" />
Run Code Online (Sandbox Code Playgroud)

expiredCSS类的定义为:

.expired {
   text-decoration: line-through;
}
Run Code Online (Sandbox Code Playgroud)

小提琴