2013-04-17 48 views
1

我有一個表,通過數據綁定與可觀察的對象(人)數組綁定。當我點擊表格的某個單元格時,一行的索引和一個單元格的索引被寫入到變量「self.currentLine」和「self.currentCell」中,而上面的輸入出現在100%寬度和100%高度上方,覆蓋數據本身。 是否有可能訪問可觀察數組中某個對象的某個字段,只使用字段的索引而不使用字段名? (實施例不self.persons [0] '名稱',但self.persons [0] [0])在可觀察的對象數組中訪問對象字段。 KnockoutJS

下面是一個代碼(JS):

function person(fullname, age, sex, married) 
{ 
    this.name = ko.observable(fullname); //string, only observable field, while i'm trying to get this working properly. 
    this.age = age;      //Data 
    this.sex = sex;      //string 
    this.married = married;    //bool 
}; 

function personViewModel() 
{ 
    var self = this; 
    self.currentLine = ko.observable(); 
    self.currentCell = ko.observable(); 
    self.columnNames = ko.observableArray([ 
       'Name', 
       'Age', 
       'Sex', 
       'Married' 
    ]); 

    self.persons = ko.observableArray([...]); 

    }; 
    self.setLine = function(index) 
    { 
     self.currentLine(index); 
    }; 
    self.setCell= function(cellIndex) 
    { 
     self.currentCell(cellIndex); 
    }; 
}; 
ko.applyBindings(new personViewModel()); 

和HTML代碼我使用:

<table> 
     <thead data-bind="template: { name: 'tableHeader', data: columnNames }" /> 
     <tbody data-bind="template: { name: 'tableContent', foreach: persons }" /> 
    </table> 

    <script id="tableHeader" type="text/html"> 
     <tr data-bind="foreach: $data"> 
       <td data-bind="text: $data, 
           css: { 'active': $root.currentItem() == $data }"> 
       </td> 
     </tr> 
    </script> 

    <script id="tableContent" type="text/html"> 
     <tr data-bind="click: $root.setLine.bind($data, $index())"> 
      <td data-bind="click: $root.setCell.bind($data, $element.cellIndex)"> 
       <span data-bind="text: name"></span> 
       <input type="text" data-bind="visible: $root.currentCell() == 0 && $index() == $root.currentLine(), 
               value: name"/> <!--fixed--> 
      </td> 
     </tr> 
    </script> 

在html中,我根據表中單擊的單元格設置輸入可見。所以現在我需要將一個單元格的值傳遞給輸入,所以我可以編輯這些數據。

更新:像往常一樣,我忘記把括號'()'後面的值:name()在輸入中。但是第二個問題出現了。據我所知,當輸入失去焦點時,必須自動改變值。但我的不會改變......

回答

3

使用輸入value結合通過小區的值:

據我所知,是沒有辦法訪問一個字段,其應該指數,讀取場從observableArray中的對象開始,可以使用以下語法: persons()[index].fieldName(),因爲該字段也是可觀察的。

希望它有幫助。

+0

好吧,但如果我不知道字段的名稱?有沒有可能通過索引或類似的東西得到它的名字? – Kamilius

+1

找到一個答案,使用Object.keys(persons()[index]),我有一個鍵數組,所以現在我可以把需要的字段名稱。 – Kamilius

相關問題