我正在处理Excel任务窗格应用。基本上它的作用是在用户输入时用无效格式(邮政编码为r1243)更改单元格的背景颜色。我创建了一个绑定并添加了一个BindingDataChanged事件处理程序,它监听数据更改。如果有任何更改,请验证格式并更改背景颜色。代码如下。
代码有点工作,但问题是onBindingDataChanges似乎永远不会结束,即使数据没有任何变化。可能有什么不对?
function listenChanges() {
Office.select("bindings#customerTableBinding").addHandlerAsync(Office.EventType.BindingDataChanged, onBindingDataChanged, function (asyncResult) {
if (asyncResult.status === "failed") {
app.showNotification('Error: ' + asyncResult.error.message);
} else {
app.showNotification('New event handler added for binding.');
}
});
}
function onBindingDataChanged(eventArgs) {
eventArgs.binding.getDataAsync({coercionType: 'table'},
function (asyncResult) {
if (asyncResult.status == 'succeeded') {
var table = new Office.TableData();
table.headers = asyncResult.value.headers;
table.rows = asyncResult.value.rows;
var column = getColumns(table);
var rows = getRows(table, column);
eventArgs.binding.setFormatsAsync([{ cells: Office.Table.Data, format: { backgroundColor: "white" } }], function (asyncResult) { });
for (var i = 0; i < rows.length; i++) {
eventArgs.binding.setFormatsAsync([{ cells: { row: rows[i], column: column }, format: { backgroundColor: "red", fontStyle: "bold" } }], function (asyncResult) { });
}
}
else
app.showNotification("The error message is " + asyncResult.error.message);
});
}
function getColumns(table) {
var column;
for (var i = 0; i < table.headers.length; i++) {
for (var j = 0; j < table.headers[i].length; j++) {
if (table.headers[i][j] == "PostalCode") {
column = j;
}
}
}
return column;
}
function getRows(table, column) {
var rows = new Array();
for (var i = 0; i < table.rows.length; i++) {
if (!isValidUSZip(table.rows[i][column])) {
rows.push(i);
}
}
return rows;
}
function isValidUSZip(zip) {
return /^\d{5}(-\d{4})?$/.test(zip);
}
答案 0 :(得分:1)
eventArgs.binding.setFormatsAsync([{cells:Office.Table.Data,format:{backgroundColor:“white”}}],function(asyncResult){});
每次更改事件触发时,您都将背景设置为白色。这将触发更改事件再次触发(导致无限循环)。要解决此问题,您可以在触发数据事件操作时删除处理程序,然后在完成更新后将其添加回来。
function addHandlerChanged() {
if (selfBinding) {
selfBinding.addHandlerAsync(
Office.EventType.BindingDataChanged, dataChangeEvent);
}
}
function removeHandlerChanged() {
if (selfBinding) {
selfBinding.removeHandlerAsync(
Office.EventType.BindingDataChanged, { handler: dataChangeEvent }, function (result) {
});
}
};
function dataChangeEvent(eventArgs) {
//remove handler
removeHandlerChanged();
// do you're table format update here
//then add the handler back
addHandlerChanged();
}