2014-07-07 54 views
0

我需要在運行時更改kogrid上的columnDefs,但沒有太多運氣。kogrid - Dyanmic ColumDefs

我默認爲視圖加載時的數據源。當用戶從下拉列表中選擇時,會觸發一個名爲ChangeDataSource的方法。在該方法中,我更改了columdefs和數據源,但kogrid仍顯示默認數據源和columndefs。

這裏是illistrate- http://jsfiddle.net/wood0615/cw56z/6/

這裏是代碼 -

查看 -

<div class="gridStyle" data-bind="koGrid: gridOptions"></div> 
     <select id="Select6" tabindex="3" style="width: 190px" data-bind=" options: InstrumentTypes, value: modalInstrumentTypeValue, optionsValue: 'OptionValue', optionsText: 'OptionText', validationOptions: { insertMessages: false }, event: { change: ChangeDataSource }"> 
     </select> 

VIEWMODEL-

var modalInstrumentTypeValue = ko.observable(); 


function mainVm(){ 
    var self = this; 
    this.modalInstrumentTypeValue = ko.observable(); 
    this.InstrumentTypes = ko.observableArray([{OptionText: "Moroni", OptionValue: 50}, 
            {OptionText: "Tiancum", OptionValue: 43}, 
            {OptionText: "Jacob", OptionValue: 27}, 
            {OptionText: "Nephi", OptionValue: 29}, 
            {OptionText: "Enos", OptionValue: 34}]); 

    this.myData = ko.observableArray([{name: "Moroni", age: 50}, 
            {name: "Tiancum", age: 43}, 
            {name: "Jacob", age: 27}, 
            {name: "Nephi", age: 29}, 
            {name: "Enos", age: 34}]); 


    this.myData2 = ko.observableArray([{Client: "Acme", Address: '123 Somewhere street'}, 
            {Client: "Johnsons", Address: '123 Here street'}, 
            {Client: "AdLib", Address: '123 Now street'}, 
            {Client: "Tough", Address: '123 Main street'}, 
            {Client: "Mars", Address: '123 Sommer street'}]); 
    this.gridOptions = { 
    data: self.myData, 
    columnDefs: [{ field: 'name', displayName: 'Client Name', width: 140 }, 
       { field: 'age', displayName: 'Age', width: 100 } 
       ]}; 

     this.saveState = function() { 

} 

     this.ChangeDataSource = function (tab) { 


     gridOptions = { 
    data: self.myData2, 
     columnDefs: [{ field: 'Client', displayName: 'Client', width: 140 }, 
       { field: 'Address', displayName: 'Address', width: 100 } 
       ]}; 
    } 
}; 


    ko.applyBindings(new mainVm()); 

我怎麼可以在代碼,使的jsfiddle當我的viewmodel中的數據源和columndefs發生變化時,視圖也是cha是否相應?

回答

2

您的ChangeDataSource函數應該更新觀察值,而不是再次設置gridOptions

this.cols = ko.observableArray([{ 
    field: 'name', 
    displayName: 'Client Name', 
    width: 140 
}, { 
    field: 'age', 
    displayName: 'Age', 
    width: 100 
}]); 

this.gridOptions = { 
    data: self.myData, 
    columnDefs: self.cols 
}; 

this.ChangeDataSource = function (tab) { 
    self.myData(self.myData2()); 
    self.cols([{ 
     field: 'Client', 
     displayName: 'Client', 
     width: 140 
    }, { 
     field: 'Address', 
     displayName: 'Address', 
     width: 100 
    }]); 
} 

Updated fiddle

+1

完美!感謝GôTô – Chris