2013-03-18 7 views
18

Ich versuche knockout.js zu verwenden, um eine <select/> Feld aufzufüllen und zu verwalten. Ich möchte, dass der Anfangswert leer ist.knockout.js - eine leere Auswahl Einstellung

Allerdings habe ich Probleme, zu versuchen, den verwalteten Wert jederzeit null zu machen, geschweige denn zu Beginn.

Betrachten wir zum Beispiel this fiddle:

HTML:

<select data-bind="options: myOptions, value: myValue"></select> aka 
<span data-bind="text: myValue"></span> 

<div> 
    <button data-bind="click: setMyValue(null)">clear the selection</button> 
    <button data-bind="click: setMyValue('one')">select "one"</button> 
    <button data-bind="click: setMyValue('four')">select "four"</button> 
</div> 
<ul data-bind="foreach: log"> 
    <li>message: <span data-bind="text: message"></span></li> 
</ul> 

JS:

function Model() { 
    var self = this; 
    self.myOptions = ['one', 'two', 'three', 'four']; 
    self.myValue = ko.observable(); 
    self.setMyValue = function (val) { 
     return function(){ 
      this.log.push({ 
       message: "ok, trying to set value as " + val 
      }); 
      self.myValue(val); 
     }; 
    }; 
    self.log = ko.observableArray([]); 
} 
var model = new Model(); 
ko.applyBindings(model); 

Die select "one" und select "four" Tasten, um die Auswahl zu ändern arbeiten, indem sie ein Update von myValue() zwingen. Das Löschen der Auswahltaste funktioniert jedoch nicht. Die Auswahl wird nicht von myValue(null), which is what I thought was the proper way to do it gelöscht.

Was mache ich falsch?

Antwort

31

Sie benötigen den Bindungssatz optionsCaption.

<select data-bind="options: myOptions, value: myValue, optionsCaption: 'select...'"></select> 

Updated Fiddle