2013-03-18 65 views
18

我正在嘗試使用knockout.js來填充和管理一個<select/>框。我希望初始值爲空。knockout.js - 設置一個空選擇

但是,我無法在任何時候強制託管值爲空,更不用說最初。

例如,考慮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); 

select "one"select "four"按鈕的工作通過強制的myValue()的更新來改變選擇。但是,清除選擇按鈕不起作用。該選擇未被myValue(null),which is what I thought was the proper way to do it清除。

我在做什麼錯?

回答