2014-02-25 29 views
5

我們正在努力實現一個複選框,並列出了以下功能:Knockout.js選中複選框,然後單擊事件

  • 點擊複選框要麼清除數組,如果有在那裏的項目,或添加新項目,如果沒有。
  • 單擊刪除按鈕時,從陣列中刪除一個項目,一旦最後一個項目被刪除,複選框會自動取消選中它自己。

我遇到的問題是,如果你點擊刪除每個數組項,然後點擊複選框添加一個空白條目,我期待複選框被再次檢查(根據檢查的可觀察),但它不是?

我有以下代碼:

http://jsfiddle.net/UBsW5/3/

<div> 
     <input type="checkbox" data-bind="checked: PreviousSurnames().length > 0, click: $root.PreviousSurnames_Click" />Previous Surname(s)? 
    </div> 
    <div data-bind="foreach: PreviousSurnames"> 
     <div> 
      <input type="text" data-bind="value: $data"> 
      <span data-bind="click: $root.removePreviousSurname">Remove</span> 
     </div> 
    </div> 


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

    self.PreviousSurnames = ko.observableArray(['SURNAME1', 'SURNAME2', 'SURNAME3']); 

    self.removePreviousSurname = function (surname) { 
     self.PreviousSurnames.remove(surname); 
    }; 

    self.PreviousSurnames_Click = function() { 
     if (self.PreviousSurnames().length === 0) { 
      self.PreviousSurnames.push(''); 
     } 
     else { 
      self.PreviousSurnames.removeAll(); 
     } 
     alet(2) 
    } 

} 

ko.applyBindings(new myViewModelExample()); 

回答

4

您需要使用計算來監視observable數組的長度。這種方式當長度達到零時,您可以自動對其作出反應。

self.surnames = ko.computed(function() { 
     var checked = true; 
     if (self.PreviousSurnames().length === 0) { 
      self.PreviousSurnames.push(''); 
      checked = false; 
     }    
     return checked; 
    }); 

現在,當清除所有名稱時,您將擁有空白文本框。如果您在複選框上更新綁定,它也會正常運行。

<input type="checkbox" data-bind="checked: surnames, click: PreviousSurnames_Click" />Previous Surname(s)? 

FIDDLE

+0

什麼的點計算的?在你的示例中,代碼被複制到計算結果和'PreviousSurnames_Click'中,並且您還需要在最近的編輯中添加'return true;'以使複選框「工作」? – nemesv

+0

計算的要點是當數組中沒有項目自動保留時作出反應。該代碼是重複的,因爲它是一個小提琴。這個例子的重構是一個簡單的過程。但是,我更新了它以刪除重複的代碼。在你的例子中,當所有項目被清除時,文本框不會出現。 –

14

如果您使用起來需要return true從你的點擊處理程序allow the browser default click actionclickchecked然後在這種情況下檢查複選框:

self.PreviousSurnames_Click = function() { 
    if (self.PreviousSurnames().length === 0) { 
     self.PreviousSurnames.push(''); 
    } 
    else { 
     self.PreviousSurnames.removeAll(); 
    } 
    return true; 
} 

演示JSFiddle

相關問題