2013-10-27 191 views
0

我有一個表單,您可以添加多個任務,每個任務都有一個標題和一個選項,如果您選擇了一個特定的選項,我想添加一個表格,您可以在其中添加一個或多個筆記。我無法弄清楚的是如何將任務的註釋綁定到該特定任務以及如何爲每個任務聆聽selectedOption?這是我第一次使用淘汰賽。敲除表單綁定foreach

<fieldset data-bind="foreach: tasks"> 
    Title:<input type="text" data-bind="value: title"/> 
    Option: <select data-bind="options: $root.option, optionsCaption: 'Select', value: selectedOption"></select> 

    <table> 
     <tbody data-bind="foreach: notes "> 
      <tr> 
       <td><input type="text" data-bind="value: note"/></td> 
      </tr>  
     </tbody> 
    </table> 
    <button data-bind="click: addRow">Add note</button> 
</fieldset> 
<button data-bind="click: addTask">Add task</button> 

回答

0

如果給每個任務selectedOption屬性和Notes屬性,它們的值將被綁定到他們的父任務。

看一看這個(小提琴:http://jsfiddle.net/jRyS7/2/):

var Note = function(note){ 
    var self = this; 
    self.note = ko.observable(note); 
} 

var Task = function(title, notes){ 
    var self = this; 
    self.title = ko.observable(title); 
    self.selectedOption = ko.observable(); 
    self.notes = ko.observableArray(); 
    for (var i = 0; i< notes.length; i++){ 
     self.notes.push(new Note(notes[i])); 
    } 
    self.addRow = function(){ 
     self.notes.push(new Note("newNote")); 
    } 
} 

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

    self.option = [ 
     "option1", 
     "option2" 
     ] 

    self.tasks = ko.observableArray([ 
     new Task("task1", ["note1.1", "note1.2"]), 
     new Task("task2", ["note2.1", "note2.2"]), 
     new Task("task3", ["note3.1", "note3.2"]) 
    ]) 

    self.addTask = function(){ 
     self.tasks.push(new Task("newTask", ["newNote1", "newNote2"])); 
    } 

} 

     ko.applyBindings(new VM()); 
+0

謝謝,偉大工程! – ana