如何防止aggrid中的onselectionchanged方法多次停止执行



我使用的是aggrid,其中我有一个选择更改的方法。所以,如果我选择7k行,它会执行7000次,这会导致页面挂起。

如果有人知道原因是多次执行,请分享。我该如何防止这种情况发生。

function onSelectionChanged() {
getSelectedRowToStore();
}
function getSelectedRowToStore() {
var myRowStorage = document.getElementById('recordJsonStore');
// Convert the JSON String into an Object so we can manipulate it
if (myRowStorage != null && myRowStorage != '') {
dataSampleAfterUpdate = JSON.parse(myRowStorage.getAttribute('data-rows'));
}
if (dataSampleAfterUpdate == null) {
dataSampleAfterUpdate = [];
}

var selectedRows = gridOptions.api.getSelectedRows(); //Here I am getting 7k on first time.But it again excecutes
var obj = Object.fromEntries(dataSampleAfterUpdate.map(e => [e.Id, e]));
selectedRows.forEach(function(selectedRow, index) {
obj[selectedRow.Id] = selectedRow;
});
dataSampleAfterUpdate = Object.values(obj);
var myRowStorage = document.getElementById('recordJsonStore');
myRowStorage.setAttribute('data-rows', JSON.stringify(dataSampleAfterUpdate));
if (dataSampleAfterUpdate.length > 0) {
document.getElementById("unsavedLabel").style.display = 'inline-block';
document.getElementById("unsaved").innerHTML = dataSampleAfterUpdate.length;
}
}
var gridOptions = {
columnDefs: columnDefs,
rowData: arr1,
checkbox: true,
rowSelection: 'multiple',
suppressRowClickSelection: true,
rowMultiSelectWithClick: true,
onSelectionChanged: onSelectionChanged,
suppressCopyRowsToClipboard: true,
animateRows: true,
defaultColDef: {
resizable: true,
sortable: true
},
enterMovesDown: true,
enterMovesDownAfterEdit: true,
//rowBuffer: 500,
enableRangeSelection: true
}

您正在经历的事情是正常的。由于您使用的是自定义函数,因此必须在行上循环并将其设置为选中。像这样的东西:

this.gridApi.forEachNode(node => {
node.setSelected(true); // or false for that matter
});

对于设置为选中的每个节点,将触发事件onSelectionChanged

遗憾的是,我不认为有任何其他方法可以做到这一点,因为agGrid上的无限模式似乎有这个限制,而且似乎没有任何修复的希望。因此,您需要通过尝试以某种方式累积onSelectionChanged事件调用来解决此问题。

在AG-Grid API中似乎仍然没有一个好的解决方案(2022年4月(。

一种变通方法/破解方法可能是在选择行的代码中捕获时间戳,并使选择事件处理程序依赖于此。像这样:

// individual row selections above
const updated = Date.now();
this.gridOptions.onSelectionChanged = event => {      
if (Date.now() - updated < 200) {
return; 
}
// complex event handler below
...

最新更新