Conditional knockout style of option elements of an "unrelated" SELECT element

The various inputs on my page are tied through a knockout to the presentation model, let the client records say. It all works fine.

Now I want to put SELECT at the top of the page containing a list of all clients. The user will select the client, the record will be retrieved from the database, and the data will be bound to the view model.

My question is about the conditional style of the elements in this SELECT list. It will be bound to an array of client objects. The definition of the Customer object has a hasExpired function :

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

The ViewModel to which the inputs on the page are bound is as follows:

      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()



     }

Knockout work; SELECT is correctly populated with a list of clients:

    <select id="customerSelect" 
             data-bind="options: allCustomers,
            optionsText: 'customerName', 
            value:   selectedCustomer />

, "expired".

SELECT . SELECT . allCustomers.

hasExpired , , , expired?

, , .

SELECT ?

+3
1

(optionsAfterRender), . . 2: ( ).

, , ,

self.setOptionStyling = function(option, item) {
   ko.applyBindingsToNode(option, {css: {expired: item.hasExpired()} }, item);
}

optionsAfterRender:

<select id="customerSelect" 
        data-bind="options: allCustomers,
                   optionsText: 'customerName', 
                   value: selectedCustomer,
                   optionsAfterRender: setOptionStyling" />

expired css :

.expired {
   text-decoration: line-through;
}

Fiddle

+7

All Articles